<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/csrf.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

requireLogin();

$pageTitle = 'Change Password';
$siteName  = 'Crop Monitor';

$errors  = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $oldPassword = $_POST['password_old']         ?? '';
        $newPassword = $_POST['password_new']         ?? '';
        $confirm     = $_POST['password_new_confirm'] ?? '';

        if ($oldPassword === '') {
            $errors[] = 'Current password is required.';
        }
        if (strlen($newPassword) < 8) {
            $errors[] = 'New password must be at least 8 characters.';
        }
        if ($newPassword !== $confirm) {
            $errors[] = 'New passwords do not match.';
        }

        if (empty($errors)) {
            if (changePassword(getCurrentUserId(), $oldPassword, $newPassword)) {
                regenerateCsrfToken();
                $success = true;
            } else {
                $errors[] = 'Current password is incorrect.';
            }
        }
    }
}

include __DIR__ . '/../layouts/header.php';
include __DIR__ . '/../layouts/navbar.php';
?>

<div id="layoutSidenav">
    <div id="layoutSidenav_nav">
        <?php include __DIR__ . '/../layouts/sidebar.php'; ?>
    </div>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">

                <h1 class="mt-4"><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Change Password</li>
                </ol>

                <div class="row justify-content-center">
                    <div class="col-xl-6 col-lg-8">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 fw-bold text-success">Update Your Password</h6>
                            </div>
                            <div class="card-body">

                                <?php if ($success): ?>
                                    <div class="alert alert-success" role="alert">
                                        <i class="fas fa-check-circle me-2"></i>Your password has been updated successfully.
                                    </div>
                                <?php endif; ?>

                                <?php if (!empty($errors)): ?>
                                    <div class="alert alert-danger" role="alert">
                                        <ul class="mb-0">
                                            <?php foreach ($errors as $e): ?>
                                                <li><?= htmlspecialchars($e, ENT_QUOTES, 'UTF-8') ?></li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                <?php endif; ?>

                                <form method="post" action="/login/change-password.php">
                                    <input type="hidden" name="csrf_token"
                                           value="<?= htmlspecialchars(generateCsrfToken(), ENT_QUOTES, 'UTF-8') ?>">

                                    <div class="mb-3">
                                        <label for="password_old" class="form-label">Current Password</label>
                                        <input type="password" class="form-control" id="password_old"
                                               name="password_old" placeholder="Current password" required>
                                    </div>

                                    <div class="mb-3">
                                        <label for="password_new" class="form-label">New Password</label>
                                        <input type="password" class="form-control" id="password_new"
                                               name="password_new" placeholder="New password (min 8 characters)" required>
                                    </div>

                                    <div class="mb-3">
                                        <label for="password_new_confirm" class="form-label">Confirm New Password</label>
                                        <input type="password" class="form-control" id="password_new_confirm"
                                               name="password_new_confirm" placeholder="Repeat new password" required>
                                    </div>

                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-key me-1"></i>Change Password
                                    </button>
                                    <a href="/dashboard/dashboard.php" class="btn btn-secondary ms-2">Cancel</a>
                                </form>

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

            </div><!-- /container-fluid -->

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