<?php
// customer/profile.php
session_start();
require_once '../app/Core/init.php';
require_once '../app/Core/DojahKYC.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: ../index.php');
    exit;
}

$page_title  = "Profile";
$active_menu = "profile";

$customerModel = new Customer();
$userModel     = new User();
$kycService    = new DojahKYC();

$customer = $customerModel->findByUserId($_SESSION['user_id']);
if (!$customer) { header('Location: ../index.php'); exit; }

$bank_details    = $userModel->getBankDetails($_SESSION['user_id']);
$kyc_record      = $kycService->getVerification((int)$_SESSION['user_id'], DojahKYC::TYPE_CUSTOMER_IDENTITY);
$is_kyc_verified = $kyc_record && $kyc_record['status'] === 'verified';
$name_locked     = (bool)($customer['name_locked'] ?? false);

// The widget callback URL includes the verification_type so kyc-callback.php
// knows which flow completed. Dojah appends ?verification_id=xxx automatically.
$widget_callback_url = KYC_CALLBACK_URL . '?verification_type=' . DojahKYC::TYPE_CUSTOMER_IDENTITY;
$widget_id           = $kycService->getWidgetId(DojahKYC::TYPE_CUSTOMER_IDENTITY);

// Flash message from kyc-callback.php redirect
$kyc_flash = $_SESSION['kyc_flash'] ?? null;
unset($_SESSION['kyc_flash']);

$success_message = '';
$error_message   = '';

// ── POST ACTIONS ──────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    switch ($action) {

        case 'update_profile':
            $updateData = [
                'phone'   => trim($_POST['phone']   ?? ''),
                'address' => trim($_POST['address'] ?? ''),
                'city'    => trim($_POST['city']    ?? ''),
                'state'   => trim($_POST['state']   ?? ''),
            ];
            if (!$name_locked) {
                $updateData['first_name'] = trim($_POST['first_name'] ?? '');
                $updateData['last_name']  = trim($_POST['last_name']  ?? '');
            }
            if ($customerModel->update($customer['id'], $updateData)) {
                $customer        = $customerModel->findByUserId($_SESSION['user_id']);
                $success_message = 'Profile updated successfully!';
            } else {
                $error_message = 'Failed to update profile. Please try again.';
            }
            break;

        case 'change_password':
            $current = $_POST['current_password'] ?? '';
            $new     = $_POST['new_password']      ?? '';
            $confirm = $_POST['confirm_password']  ?? '';

            if (empty($current) || empty($new) || empty($confirm)) {
                $error_message = 'All password fields are required.';
            } elseif ($new !== $confirm) {
                $error_message = 'New passwords do not match.';
            } elseif (strlen($new) < 6) {
                $error_message = 'New password must be at least 6 characters.';
            } elseif (!$userModel->verifyPassword($_SESSION['user_id'], $current)) {
                $error_message = 'Current password is incorrect.';
            } else {
                $userModel->updatePassword($_SESSION['user_id'], $new)
                    ? $success_message = 'Password changed successfully!'
                    : $error_message   = 'Failed to change password. Please try again.';
            }
            break;

        case 'update_bank':
            $bank_name      = trim($_POST['bank_name']      ?? '');
            $account_name   = trim($_POST['account_name']   ?? '');
            $account_number = trim($_POST['account_number'] ?? '');

            if (empty($bank_name) || empty($account_name) || empty($account_number)) {
                $error_message = 'All bank detail fields are required.';
            } elseif (!preg_match('/^[0-9]{10}$/', $account_number)) {
                $error_message = 'Account number must be exactly 10 digits.';
            } else {
                if ($userModel->updateBankDetails($_SESSION['user_id'], compact('bank_name','account_name','account_number'))) {
                    $bank_details    = $userModel->getBankDetails($_SESSION['user_id']);
                    $success_message = 'Bank details updated successfully!';
                } else {
                    $error_message = 'Failed to update bank details. Please try again.';
                }
            }
            break;
    }
}

$page_title = 'My Profile — ' . APP_NAME;
include '../templates/layouts/customer/head.php';
?>

<body class="fixed sidebar-mini">
<div class="wrapper">
    <nav class="sidebar">
        <div class="sidebar-header">
            <?php include '../templates/layouts/customer/navbar.php'; ?>
        </div>
    </nav>

    <div class="content-wrapper">
        <div class="main-content">
            <?php include '../templates/layouts/customer/header.php'; ?>

            <div class="page-header">
                <div class="page-title">
                    <h1>Profile Settings</h1>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Profile</li>
                    </ul>
                </div>
            </div>

            <?php if ($success_message): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fa fa-check-circle me-2"></i><?= htmlspecialchars($success_message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fa fa-exclamation-circle me-2"></i><?= htmlspecialchars($error_message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($kyc_flash): ?>
                <div class="alert alert-<?= htmlspecialchars($kyc_flash['type']) ?> alert-dismissible fade show">
                    <i class="fa fa-<?= $kyc_flash['type'] === 'success' ? 'check-circle' : 'info-circle' ?> me-2"></i>
                    <?= htmlspecialchars($kyc_flash['message']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- ── SECTION 1: Identity Verification ──────────────── -->
            <div class="card mb-4" id="kycSection">
                <div class="card-header <?= $is_kyc_verified ? 'bg-success' : 'bg-warning' ?> text-white">
                    <h6 class="fs-17 fw-semi-bold mb-0">
                        <i class="fa fa-shield-alt me-2"></i>
                        Identity Verification
                        <?php if ($is_kyc_verified): ?>
                            <span class="badge bg-light text-success ms-2">
                                <i class="fa fa-check-circle"></i> Verified
                            </span>
                        <?php else: ?>
                            <span class="badge bg-light text-dark ms-2">
                                <i class="fa fa-exclamation-triangle"></i> Not Verified
                            </span>
                        <?php endif; ?>
                    </h6>
                </div>
                <div class="card-body">

                    <?php if ($is_kyc_verified): ?>
                        <div class="alert alert-success d-flex align-items-start mb-0">
                            <i class="fa fa-check-circle fa-2x me-3 mt-1"></i>
                            <div>
                                <strong>Your identity has been verified!</strong><br>
                                <span class="text-muted" style="font-size:13px;">
                                    Verified as:
                                    <strong><?= htmlspecialchars(trim(($kyc_record['verified_first_name'] ?? '') . ' ' . ($kyc_record['verified_last_name'] ?? ''))) ?></strong>
                                    &nbsp;|&nbsp;
                                    ID Type: <strong><?= htmlspecialchars(strtoupper($kyc_record['id_type'] ?? 'N/A')) ?></strong>
                                    &nbsp;|&nbsp;
                                    Date: <strong><?= date('M d, Y', strtotime($kyc_record['updated_at'])) ?></strong>
                                </span>
                            </div>
                        </div>

                    <?php else: ?>

                        <?php if ($kyc_record && $kyc_record['status'] === 'failed'): ?>
                            <div class="alert alert-warning">
                                <i class="fa fa-exclamation-triangle me-2"></i>
                                Your previous attempt failed: <strong><?= htmlspecialchars($kyc_record['failure_reason'] ?? '') ?></strong>.
                                Please try again.
                            </div>
                        <?php endif; ?>

                        <div class="alert alert-info mb-3">
                            <i class="fa fa-info-circle me-2"></i>
                            <strong>Why verify?</strong>
                            You must verify your identity before booking any item.
                            Once verified, your name will be locked to match your ID.
                        </div>

                        <?php if ($widget_id): ?>
                            <script defer src="https://widget.dojah.io/websdk.js"></script>
                            <dojah-button
                                widgetId="<?= htmlspecialchars($widget_id) ?>"
                                text="Verify My Identity"
                                textColor="#FFFFFF"
                                backgroundColor="#f0a500">
                            </dojah-button>
                            <p class="text-muted mt-2 mb-0" style="font-size:12px;">
                                <i class="fa fa-lock me-1"></i>
                                One-time verification. Your data is handled securely by Dojah.
                            </p>


                        <?php else: ?>
                            <div class="alert alert-danger">
                                <i class="fa fa-exclamation-circle me-2"></i>
                                Widget not configured. Please contact support.
                            </div>
                        <?php endif; ?>

                    <?php endif; ?>
                </div>
            </div>

            <!-- ── SECTION 2: Profile Details ────────────────────── -->
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h6 class="fs-17 fw-semi-bold mb-0">
                        Profile Details
                        <?php if ($name_locked): ?>
                            <span class="badge bg-light text-success ms-2">
                                <i class="fa fa-lock"></i> Name locked by KYC
                            </span>
                        <?php endif; ?>
                    </h6>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="update_profile">
                        <div class="row g-4">
                            <div class="col-sm-6 col-lg-4">
                                <label class="required fw-medium mb-2">First Name</label>
                                <input type="text" name="first_name" class="form-control"
                                       value="<?= htmlspecialchars($customer['first_name']) ?>"
                                       <?= $name_locked ? 'readonly' : 'required' ?>>
                                <?php if ($name_locked): ?>
                                    <small class="text-muted"><i class="fa fa-lock"></i> Set by KYC</small>
                                <?php endif; ?>
                            </div>
                            <div class="col-sm-6 col-lg-4">
                                <label class="required fw-medium mb-2">Last Name</label>
                                <input type="text" name="last_name" class="form-control"
                                       value="<?= htmlspecialchars($customer['last_name']) ?>"
                                       <?= $name_locked ? 'readonly' : 'required' ?>>
                                <?php if ($name_locked): ?>
                                    <small class="text-muted"><i class="fa fa-lock"></i> Set by KYC</small>
                                <?php endif; ?>
                            </div>
                            <div class="col-lg-4">
                                <label class="fw-medium mb-2">Email Address</label>
                                <input type="email" class="form-control"
                                       value="<?= htmlspecialchars($customer['email']) ?>" readonly>
                                <small class="text-muted">Email cannot be changed</small>
                            </div>
                            <div class="col-sm-6 col-lg-4">
                                <label class="required fw-medium mb-2">Phone Number</label>
                                <input type="text" name="phone" class="form-control" required
                                       value="<?= htmlspecialchars($customer['phone'] ?? '') ?>">
                            </div>
                            <div class="col-sm-6 col-lg-4">
                                <label class="fw-medium mb-2">City</label>
                                <input type="text" name="city" class="form-control"
                                       value="<?= htmlspecialchars($customer['city'] ?? '') ?>">
                            </div>
                            <div class="col-sm-6 col-lg-4">
                                <label class="fw-medium mb-2">State</label>
                                <input type="text" name="state" class="form-control"
                                       value="<?= htmlspecialchars($customer['state'] ?? '') ?>">
                            </div>
                            <div class="col-12">
                                <label class="fw-medium mb-2">Address</label>
                                <textarea name="address" class="form-control" rows="3"><?= htmlspecialchars($customer['address'] ?? '') ?></textarea>
                            </div>
                        </div>
                        <div class="mt-4">
                            <button type="submit" class="btn btn-primary">
                                <i class="fa fa-save me-2"></i>Update Profile
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- ── SECTION 3: Bank Details ────────────────────────── -->
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h6 class="fs-17 fw-semi-bold mb-0">
                        <i class="fa fa-university me-2"></i>Bank Account Details
                    </h6>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle me-2"></i>
                        Your bank details are used for refunds, payouts, and financial transactions.
                    </div>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_bank">
                        <div class="row g-4">
                            <div class="col-sm-6 col-lg-4">
                                <label class="required fw-medium mb-2">Bank Name</label>
                                <select name="bank_name" class="form-control" required>
                                    <option value="">Select Bank</option>
                                    <?php foreach ([
                                        'Access Bank','Citibank','Diamond Bank','Ecobank Nigeria',
                                        'Fidelity Bank','First Bank of Nigeria','First City Monument Bank',
                                        'Guaranty Trust Bank','Heritage Bank','Keystone Bank','Polaris Bank',
                                        'Providus Bank','Stanbic IBTC Bank','Standard Chartered Bank',
                                        'Sterling Bank','Union Bank of Nigeria','United Bank for Africa',
                                        'Unity Bank','Wema Bank','Zenith Bank',
                                    ] as $bank): ?>
                                        <option value="<?= $bank ?>"
                                                <?= ($bank_details['bank_name'] ?? '') === $bank ? 'selected' : '' ?>>
                                            <?= $bank ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-sm-6 col-lg-4">
                                <label class="required fw-medium mb-2">Account Name</label>
                                <input type="text" name="account_name" class="form-control" required
                                       value="<?= htmlspecialchars($bank_details['account_name'] ?? '') ?>">
                            </div>
                            <div class="col-sm-6 col-lg-4">
                                <label class="required fw-medium mb-2">Account Number</label>
                                <input type="text" name="account_number" class="form-control" required
                                       pattern="[0-9]{10}" maxlength="10"
                                       value="<?= htmlspecialchars($bank_details['account_number'] ?? '') ?>">
                                <small class="text-muted">10-digit account number</small>
                            </div>
                        </div>
                        <div class="mt-4">
                            <button type="submit" class="btn btn-success">
                                <i class="fa fa-university me-2"></i>Update Bank Details
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- ── SECTION 4: Change Password ────────────────────── -->
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h6 class="fs-17 fw-semi-bold mb-0">Change Password</h6>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="change_password">
                        <div class="row g-4">
                            <div class="col-sm-6">
                                <label class="required fw-medium mb-2">Current Password</label>
                                <input type="password" name="current_password" class="form-control" required>
                            </div>
                            <div class="col-sm-6">
                                <label class="required fw-medium mb-2">New Password</label>
                                <input type="password" name="new_password" class="form-control" required minlength="6">
                            </div>
                            <div class="col-sm-12">
                                <label class="required fw-medium mb-2">Confirm New Password</label>
                                <input type="password" name="confirm_password" class="form-control" required minlength="6">
                            </div>
                        </div>
                        <div class="mt-4">
                            <button type="submit" class="btn btn-primary">
                                <i class="fa fa-lock me-2"></i>Change Password
                            </button>
                        </div>
                    </form>
                </div>
            </div>

        </div>
    </div>
</div>

<?php include '../templates/layouts/customer/footer.php'; ?>
</body>
</html>