<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];
$error = ''; $success = '';
$tab = $_GET['tab'] ?? 'info';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) { $error = 'Invalid request.'; goto done; }
    $action = $_POST['action'] ?? '';

    if ($action === 'update_profile') {
        $fname   = trim($_POST['first_name'] ?? '');
        $lname   = trim($_POST['last_name'] ?? '');
        $phone   = trim($_POST['phone'] ?? '');
        $dob     = $_POST['date_of_birth'] ?? '';
        $address = trim($_POST['address'] ?? '');
        $city    = trim($_POST['city'] ?? '');
        $country = trim($_POST['country'] ?? '');
        $state   = trim($_POST['state'] ?? '');
        $postal  = trim($_POST['postal_code'] ?? '');
        $gender  = $_POST['gender'] ?? '';
        $occ     = trim($_POST['occupation'] ?? '');
        $emp     = trim($_POST['employer'] ?? '');

        if (!$fname || !$lname) { $error = 'Name is required.'; goto done; }

        // Avatar upload
        $avatar = $currentUser['avatar'];
        if (!empty($_FILES['avatar']['name'])) {
            $newAv = uploadFile($_FILES['avatar'], AVATAR_PATH, ['image/jpeg','image/png','image/gif','image/webp']);
            if ($newAv) {
                if ($avatar && file_exists(AVATAR_PATH . $avatar)) unlink(AVATAR_PATH . $avatar);
                $avatar = $newAv;
            } else {
                $error = 'Avatar upload failed. Use JPG/PNG/GIF/WEBP under 5MB.'; goto done;
            }
        }

        $pdo->prepare("UPDATE users SET first_name=?,last_name=?,phone=?,date_of_birth=?,address=?,city=?,country=?,state=?,postal_code=?,gender=?,occupation=?,employer=?,avatar=? WHERE id=?")->execute([$fname,$lname,$phone,$dob,$address,$city,$country,$state,$postal,$gender,$occ,$emp,$avatar,$uid]);
        logActivity($pdo, $uid, null, 'profile_update', 'User updated their profile');
        $success = 'Profile updated successfully.'; $currentUser = getUserById($pdo, $uid); $tab = 'info';
    }

    if ($action === 'change_password') {
        $cur  = $_POST['current_password'] ?? '';
        $new  = $_POST['new_password'] ?? '';
        $conf = $_POST['confirm_password'] ?? '';
        if (!password_verify($cur, $currentUser['password'])) { $error = 'Current password is incorrect.'; goto done; }
        if (strlen($new) < 8) { $error = 'New password must be at least 8 characters.'; goto done; }
        if ($new !== $conf) { $error = 'Passwords do not match.'; goto done; }
        $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($new, PASSWORD_DEFAULT), $uid]);
        logActivity($pdo, $uid, null, 'password_change', 'User changed their password');
        $success = 'Password changed successfully.'; $tab = 'security';
    }

    if ($action === 'change_pin') {
        $cur  = $_POST['current_pin'] ?? '';
        $new  = $_POST['new_pin'] ?? '';
        $conf = $_POST['confirm_pin'] ?? '';
        if (!preg_match('/^\d{4}$/', $new)) { $error = 'PIN must be exactly 4 digits.'; goto done; }
        if ($new !== $conf) { $error = 'PINs do not match.'; goto done; }
        if (!password_verify($cur, $currentUser['pin']) && $cur !== $currentUser['pin']) { $error = 'Current PIN is incorrect.'; goto done; }
        $pdo->prepare("UPDATE users SET pin=? WHERE id=?")->execute([password_hash($new, PASSWORD_DEFAULT), $uid]);
        logActivity($pdo, $uid, null, 'pin_change', 'User changed their transaction PIN');
        $success = 'Transaction PIN updated successfully.'; $tab = 'security';
    }
}
done:
$pageTitle = 'My Profile';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container" style="max-width:860px;">
<div class="page-title"><i class="fa fa-user-cog me-2 text-danger"></i>My Profile</div>

<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= sanitize($success) ?></div><?php endif; ?>

<div class="row g-4">
  <!-- Sidebar card -->
  <div class="col-md-3">
    <div class="card text-center p-3">
      <div class="mb-2">
        <?php if ($currentUser['avatar']): ?>
        <img src="/uploads/avatars/<?= sanitize($currentUser['avatar']) ?>" class="rounded-circle" width="80" height="80" style="object-fit:cover;border:3px solid var(--primary)">
        <?php else: ?>
        <div style="width:80px;height:80px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:2rem;margin:auto;"><i class="fa fa-user"></i></div>
        <?php endif; ?>
      </div>
      <h6 class="fw-bold mb-0"><?= sanitize($currentUser['first_name'].' '.$currentUser['last_name']) ?></h6>
      <small class="text-muted"><?= sanitize($currentUser['email']) ?></small>
      <hr>
      <div class="d-flex justify-content-between small"><span class="text-muted">Account</span><strong><?= maskAccount($currentUser['account_number']) ?></strong></div>
      <div class="d-flex justify-content-between small mt-1"><span class="text-muted">KYC</span><?= statusBadge($currentUser['kyc_status']) ?></div>
      <div class="d-flex justify-content-between small mt-1"><span class="text-muted">Status</span><?= statusBadge($currentUser['account_status']) ?></div>
    </div>
    <div class="list-group mt-2">
      <a href="?tab=info" class="list-group-item list-group-item-action <?= $tab==='info'?'active':'' ?>"><i class="fa fa-user me-2"></i>Personal Info</a>
      <a href="?tab=security" class="list-group-item list-group-item-action <?= $tab==='security'?'active':'' ?>"><i class="fa fa-shield-alt me-2"></i>Security</a>
      <a href="?tab=beneficiaries" class="list-group-item list-group-item-action <?= $tab==='beneficiaries'?'active':'' ?>"><i class="fa fa-users me-2"></i>Beneficiaries</a>
    </div>
  </div>

  <!-- Main content -->
  <div class="col-md-9">
    <?php if ($tab === 'info'): ?>
    <div class="card">
      <div class="card-header">Personal Information</div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
          <?= csrf_field() ?><input type="hidden" name="action" value="update_profile">
          <div class="row g-3">
            <div class="col-12 text-center">
              <label class="fw-bold small d-block mb-1">Profile Photo</label>
              <input type="file" name="avatar" class="form-control form-control-sm" accept="image/*" style="max-width:280px;margin:auto;">
            </div>
            <div class="col-md-6"><label class="form-label">First Name *</label><input type="text" name="first_name" class="form-control" value="<?= sanitize($currentUser['first_name']) ?>" required></div>
            <div class="col-md-6"><label class="form-label">Last Name *</label><input type="text" name="last_name" class="form-control" value="<?= sanitize($currentUser['last_name']) ?>" required></div>
            <div class="col-md-6"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control" value="<?= sanitize($currentUser['phone']??'') ?>"></div>
            <div class="col-md-6"><label class="form-label">Date of Birth</label><input type="date" name="date_of_birth" class="form-control" value="<?= sanitize($currentUser['date_of_birth']??'') ?>"></div>
            <div class="col-md-6"><label class="form-label">Gender</label>
              <select name="gender" class="form-select">
                <option value="">Select</option>
                <option value="male" <?= $currentUser['gender']==='male'?'selected':'' ?>>Male</option>
                <option value="female" <?= $currentUser['gender']==='female'?'selected':'' ?>>Female</option>
                <option value="other" <?= $currentUser['gender']==='other'?'selected':'' ?>>Other</option>
              </select>
            </div>
            <div class="col-md-6"><label class="form-label">Occupation</label><input type="text" name="occupation" class="form-control" value="<?= sanitize($currentUser['occupation']??'') ?>"></div>
            <div class="col-md-6"><label class="form-label">Employer</label><input type="text" name="employer" class="form-control" value="<?= sanitize($currentUser['employer']??'') ?>"></div>
            <div class="col-md-6"><label class="form-label">Country</label><input type="text" name="country" class="form-control" value="<?= sanitize($currentUser['country']??'') ?>"></div>
            <div class="col-12"><label class="form-label">Address</label><textarea name="address" class="form-control" rows="2"><?= sanitize($currentUser['address']??'') ?></textarea></div>
            <div class="col-md-4"><label class="form-label">City</label><input type="text" name="city" class="form-control" value="<?= sanitize($currentUser['city']??'') ?>"></div>
            <div class="col-md-4"><label class="form-label">State</label><input type="text" name="state" class="form-control" value="<?= sanitize($currentUser['state']??'') ?>"></div>
            <div class="col-md-4"><label class="form-label">Postal Code</label><input type="text" name="postal_code" class="form-control" value="<?= sanitize($currentUser['postal_code']??'') ?>"></div>
          </div>
          <button class="btn btn-primary mt-3">Save Changes</button>
        </form>
      </div>
    </div>

    <?php elseif ($tab === 'security'): ?>
    <div class="row g-3">
      <div class="col-12">
        <div class="card">
          <div class="card-header"><i class="fa fa-key me-2"></i>Change Password</div>
          <div class="card-body">
            <form method="POST">
              <?= csrf_field() ?><input type="hidden" name="action" value="change_password">
              <div class="row g-3">
                <div class="col-12"><label class="form-label">Current Password</label><input type="password" name="current_password" class="form-control" required></div>
                <div class="col-md-6"><label class="form-label">New Password</label><input type="password" name="new_password" class="form-control" minlength="8" required></div>
                <div class="col-md-6"><label class="form-label">Confirm Password</label><input type="password" name="confirm_password" class="form-control" required></div>
              </div>
              <button class="btn btn-warning mt-3">Update Password</button>
            </form>
          </div>
        </div>
      </div>
      <div class="col-12">
        <div class="card">
          <div class="card-header"><i class="fa fa-lock me-2"></i>Change Transaction PIN</div>
          <div class="card-body">
            <form method="POST">
              <?= csrf_field() ?><input type="hidden" name="action" value="change_pin">
              <div class="row g-3">
                <div class="col-md-4"><label class="form-label">Current PIN</label><input type="password" name="current_pin" class="form-control" maxlength="4" pattern="\d{4}" required></div>
                <div class="col-md-4"><label class="form-label">New PIN</label><input type="password" name="new_pin" class="form-control" maxlength="4" pattern="\d{4}" required></div>
                <div class="col-md-4"><label class="form-label">Confirm PIN</label><input type="password" name="confirm_pin" class="form-control" maxlength="4" pattern="\d{4}" required></div>
              </div>
              <button class="btn btn-danger mt-3">Update PIN</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    <?php elseif ($tab === 'beneficiaries'): ?>
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        Saved Beneficiaries
        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addBenModal"><i class="fa fa-plus me-1"></i>Add</button>
      </div>
      <div class="table-responsive">
        <table class="table mb-0">
          <thead><tr><th>Name</th><th>Account</th><th>Bank</th><th>Type</th><th>Fav</th><th></th></tr></thead>
          <tbody>
          <?php
          $bens = $pdo->prepare("SELECT * FROM beneficiaries WHERE user_id=? ORDER BY is_favourite DESC,created_at DESC");
          $bens->execute([$uid]); $benList = $bens->fetchAll();
          if (empty($benList)): ?>
          <tr><td colspan="6" class="text-center text-muted py-3">No saved beneficiaries.</td></tr>
          <?php else: foreach ($benList as $b): ?>
          <tr>
            <td><?= sanitize($b['beneficiary_name']) ?><?php if($b['nickname']): ?><br><small class="text-muted"><?= sanitize($b['nickname']) ?></small><?php endif; ?></td>
            <td><?= maskAccount($b['account_number']) ?></td>
            <td><?= sanitize($b['bank_name']??'') ?></td>
            <td><?= statusBadge($b['transfer_type']) ?></td>
            <td><?= $b['is_favourite']?'⭐':'—' ?></td>
            <td><a href="?tab=beneficiaries&del_ben=<?= $b['id'] ?>" class="btn btn-xs btn-outline-danger" data-confirm="Delete this beneficiary?"><i class="fa fa-trash"></i></a></td>
          </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    // Handle beneficiary deletion
    if (isset($_GET['del_ben'])) {
        $pdo->prepare("DELETE FROM beneficiaries WHERE id=? AND user_id=?")->execute([(int)$_GET['del_ben'], $uid]);
        header('Location: ?tab=beneficiaries'); exit;
    }
    // Handle add beneficiary
    if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='add_beneficiary') {
        verify_csrf();
        $pdo->prepare("INSERT INTO beneficiaries (user_id,nickname,beneficiary_name,account_number,bank_name,swift_code,country,transfer_type) VALUES (?,?,?,?,?,?,?,?)")->execute([$uid,$_POST['nickname']??'',$_POST['ben_name'],$_POST['ben_account'],$_POST['ben_bank']??'',$_POST['ben_swift']??'',$_POST['ben_country']??'',$_POST['transfer_type']??'local']);
        header('Location: ?tab=beneficiaries'); exit;
    }
    ?>
    <?php endif; ?>
  </div>
</div>
</div></div>
<?php include 'includes/footer.php'; ?>

<!-- Add Beneficiary Modal -->
<div class="modal fade" id="addBenModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Add Beneficiary</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="add_beneficiary">
    <div class="mb-2"><label class="form-label">Full Name *</label><input type="text" name="ben_name" class="form-control" required></div>
    <div class="mb-2"><label class="form-label">Nickname</label><input type="text" name="nickname" class="form-control"></div>
    <div class="mb-2"><label class="form-label">Account Number *</label><input type="text" name="ben_account" class="form-control" required></div>
    <div class="mb-2"><label class="form-label">Bank Name</label><input type="text" name="ben_bank" class="form-control"></div>
    <div class="mb-2"><label class="form-label">SWIFT Code</label><input type="text" name="ben_swift" class="form-control"></div>
    <div class="mb-2"><label class="form-label">Country</label><input type="text" name="ben_country" class="form-control"></div>
    <div class="mb-2"><label class="form-label">Type</label>
      <select name="transfer_type" class="form-select"><option value="local">Local</option><option value="international">International</option></select>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary">Save</button></div>
  </form>
</div></div></div>
</body></html>
