<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

// Admin can change anyone's password; staff can only change their own
$targetId = (int)($_GET['id'] ?? currentUserId());
$isAdmin  = currentUserRole() === 'admin';

if (!$isAdmin && $targetId !== currentUserId()) {
    setFlash('danger','Access denied.'); header('Location: ' . APP_URL . '/dashboard.php'); exit;
}

$userRow = $pdo->prepare("SELECT id, name, email FROM users WHERE id=?");
$userRow->execute([$targetId]);
$userRow = $userRow->fetch();
if (!$userRow) { setFlash('danger','User not found.'); header('Location: ' . APP_URL . '/dashboard.php'); exit; }

$pageTitle = 'Change Password';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: user_change_password.php?id='.$targetId); exit;
    }

    $newPass  = $_POST['new_password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';

    // If staff changing own password, require current password
    if (!$isAdmin || $targetId === currentUserId()) {
        $current = $_POST['current_password'] ?? '';
        $dbRow   = $pdo->prepare("SELECT password FROM users WHERE id=?");
        $dbRow->execute([currentUserId()]);
        $dbRow   = $dbRow->fetch();
        if (!password_verify($current, $dbRow['password'])) {
            $errors[] = 'Current password is incorrect.';
        }
    }

    if (strlen($newPass) < 6) $errors[] = 'New password must be at least 6 characters.';
    if ($newPass !== $confirm)  $errors[] = 'Passwords do not match.';

    if (empty($errors)) {
        $hash = password_hash($newPass, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hash, $targetId]);
        setFlash('success', 'Password changed successfully for ' . $userRow['name'] . '.');
        // Redirect back
        if ($isAdmin && $targetId !== currentUserId()) {
            header('Location: users.php');
        } else {
            header('Location: ' . APP_URL . '/modules/settings.php');
        }
        exit;
    }
}

require_once __DIR__ . '/../../includes/header.php';
$selfChange = ($targetId === currentUserId());
?>
<div class="page-header">
    <h2><?= $selfChange ? 'Change Your Password' : 'Change Password — ' . sanitize($userRow['name']) ?></h2>
    <?php if ($isAdmin && !$selfChange): ?>
    <a href="users.php" class="btn btn-secondary"><?= icon('arrow-left') ?> Back</a>
    <?php endif; ?>
</div>

<?php if ($errors): ?>
<div class="alert alert-danger"><?= icon('alert-circle') ?> <?= implode('<br>', array_map('sanitize', $errors)) ?></div>
<?php endif; ?>

<div class="card" style="max-width:420px;">
<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">

    <?php if ($selfChange || !$isAdmin): ?>
    <div class="form-group">
        <label>Current Password</label>
        <input type="password" name="current_password" required>
    </div>
    <?php endif; ?>

    <?php if ($isAdmin && !$selfChange): ?>
    <div class="alert alert-info" style="margin-bottom:16px;">
        <?= icon('info-circle') ?> You are setting a new password for <strong><?= sanitize($userRow['name']) ?></strong>. No current password needed.
    </div>
    <?php endif; ?>

    <div class="form-group">
        <label>New Password</label>
        <input type="password" name="new_password" required minlength="6">
    </div>
    <div class="form-group">
        <label>Confirm New Password</label>
        <input type="password" name="confirm_password" required>
    </div>

    <button type="submit" class="btn btn-primary"><?= icon('key') ?> Update Password</button>
    <?php if ($selfChange): ?>
    <a href="<?= APP_URL ?>/modules/settings.php" class="btn btn-secondary">Cancel</a>
    <?php else: ?>
    <a href="users.php" class="btn btn-secondary">Cancel</a>
    <?php endif; ?>
</form>
</div>

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