<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();
$errors = [];
$success = false;

$userId = $_SESSION['user_id'];
$user = $db->get("SELECT * FROM users WHERE id = ?", [$userId]);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $firstName = trim($_POST['first_name'] ?? '');
    $lastName = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    if ($firstName === '') {
        $errors[] = 'First name is required.';
    }
    if ($lastName === '') {
        $errors[] = 'Last name is required.';
    }
    if ($email === '') {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format.';
    }

    // Check email uniqueness
    $existing = $db->get("SELECT id FROM users WHERE email = ? AND id != ?", [$email, $userId]);
    if ($existing) {
        $errors[] = 'Email already exists.';
    }

    // Password change validation
    if ($newPassword !== '') {
        if ($currentPassword === '') {
            $errors[] = 'Current password is required to change password.';
        } elseif (!verifyPassword($currentPassword, $user['password'])) {
            $errors[] = 'Current password is incorrect.';
        } elseif ($newPassword !== $confirmPassword) {
            $errors[] = 'New passwords do not match.';
        } elseif (strlen($newPassword) < 8) {
            $errors[] = 'New password must be at least 8 characters long.';
        }
    }

    if (empty($errors)) {
        try {
            $userData = [
                'first_name' => $firstName,
                'last_name' => $lastName,
                'email' => $email,
                'updated_at' => formatDate(),
            ];

            if ($newPassword !== '') {
                $userData['password'] = hashPassword($newPassword);
            }

            $db->update('users', $userData, 'id = ?', [$userId]);
            $_SESSION['flash']['success'] = 'Profile updated successfully.';
            header('Location: profile.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

$pageTitle = 'Profile';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Profile</h1>
    <p class="text-muted mb-0">Update your profile information</p>
  </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
      <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
          <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
<?php endif; ?>

<div class="row">
  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Personal Information</h5>
      </div>
      <div class="card-body">
        <form method="post" action="">
          <div class="row mb-3">
            <div class="col-md-6">
              <label for="first_name" class="form-label">First Name</label>
              <input type="text" name="first_name" id="first_name" class="form-control" required value="<?php echo htmlspecialchars($_POST['first_name'] ?? ($user['first_name'] ?? '')); ?>">
            </div>
            <div class="col-md-6">
              <label for="last_name" class="form-label">Last Name</label>
              <input type="text" name="last_name" id="last_name" class="form-control" required value="<?php echo htmlspecialchars($_POST['last_name'] ?? ($user['last_name'] ?? '')); ?>">
            </div>
          </div>

          <div class="row mb-3">
            <div class="col-md-6">
              <label for="email" class="form-label">Email</label>
              <input type="email" name="email" id="email" class="form-control" required value="<?php echo htmlspecialchars($_POST['email'] ?? ($user['email'] ?? '')); ?>">
            </div>
            <div class="col-md-6">
              <label for="username" class="form-label">Username</label>
              <input type="text" name="username" id="username" class="form-control" value="<?php echo htmlspecialchars($user['username'] ?? ''); ?>" readonly>
              <small class="text-muted">Username cannot be changed</small>
            </div>
          </div>

          <hr class="my-4">

          <h5 class="mb-3">Change Password</h5>
          <div class="row mb-3">
            <div class="col-md-4">
              <label for="current_password" class="form-label">Current Password</label>
              <input type="password" name="current_password" id="current_password" class="form-control">
            </div>
            <div class="col-md-4">
              <label for="new_password" class="form-label">New Password</label>
              <input type="password" name="new_password" id="new_password" class="form-control">
            </div>
            <div class="col-md-4">
              <label for="confirm_password" class="form-label">Confirm New Password</label>
              <input type="password" name="confirm_password" id="confirm_password" class="form-control">
            </div>
          </div>

          <div class="d-flex justify-content-end">
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-save me-2"></i>Update Profile
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <div class="col-md-4">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Account Info</h5>
      </div>
      <div class="card-body">
        <div class="text-center mb-3">
          <div class="avatar avatar-xl">
            <div class="avatar-initial rounded-circle bg-primary">
              <?php echo strtoupper(substr($user['first_name'] ?? '', 0, 1) . substr($user['last_name'] ?? '', 0, 1)); ?>
            </div>
          </div>
        </div>
        <div class="text-center">
          <h6><?php echo htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?></h6>
          <p class="text-muted"><?php echo htmlspecialchars($user['email'] ?? ''); ?></p>
          <p class="text-muted">Role: <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $_SESSION['role'] ?? ''))); ?></p>
          <p class="text-muted">Joined: <?php echo htmlspecialchars($user['created_at'] ?? ''); ?></p>
        </div>
      </div>
    </div>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
