<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include("check_installation.php");

include("fetch_settings.php");

if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

// Redirect if not logged in
if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

if (isset($_POST["button"])) {
    $oldpass = $_POST['oldpass'];
    $newpass = $_POST['newpass'];
    $confpass = $_POST['confpass'];

    // Password validation rules
    $password_errors = [];
    if (strlen($newpass) < 8) {
        $password_errors[] = "New password must be at least 8 characters long.";
    }
    if (!preg_match("/[0-9]/", $newpass)) {
        $password_errors[] = "New password must contain at least one number.";
    }
    if (!preg_match("/[a-zA-Z]/", $newpass)) {
        $password_errors[] = "New password must contain at least one letter.";
    }
    if ($newpass !== $confpass) {
        $password_errors[] = "New password and confirm password do not match.";
    }

    if (empty($password_errors)) {
        // Step 1: Fetch current password for this admin
        $sql_check = "SELECT password FROM administrator WHERE username = ?";
        if ($stmt_check = $con->prepare($sql_check)) {
            $stmt_check->bind_param("i", $_SESSION['adminid']);
            $stmt_check->execute();
            $result = $stmt_check->get_result();

            if ($row = $result->fetch_assoc()) {
                if ($row['password'] === $oldpass) {
                    // Step 2: Update with new password
                    $sql_update = "UPDATE administrator SET password = ? WHERE username= ?";
                    if ($stmt_update = $con->prepare($sql_update)) {
                        $stmt_update->bind_param("si", $newpass, $_SESSION['adminid']);
                        $stmt_update->execute();

                        if ($stmt_update->affected_rows > 0) {
                            $_SESSION['message'] = ['type' => 'success', 'text' => 'Your admin password has been updated successfully!'];
                        } else {
                            $_SESSION['message'] = ['type' => 'error', 'text' => 'Password update was not successful.'];
                        }
                        $stmt_update->close();
                    } else {
                        $_SESSION['message'] = ['type' => 'error', 'text' => 'Database error: Unable to prepare update statement.'];
                    }
                } else {
                    $_SESSION['message'] = ['type' => 'error', 'text' => 'The current password you entered is incorrect.'];
                }
            }
            $stmt_check->close();
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Database error: Unable to prepare check statement.'];
        }
    } else {
        // Validation failed, show all password errors
        $_SESSION['message'] = ['type' => 'error', 'text' => implode('<br>', $password_errors)];
    }

    header("Location: adminpass.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Change Password</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <meta name="description" content="">
	<link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/choices/css/choices.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>

<body>
<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">Admin Password</h1>
                    </div>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">Change password</h5>
                </div>

                <div class="card-body">
                    <?php if (isset($_SESSION['message'])): 
                        $message = $_SESSION['message'];
                        unset($_SESSION['message']);
                    ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    icon: '<?= $message['type']; ?>',
                                    title: '<?= $message['type'] === 'success' ? 'Success!' : 'Error!'; ?>',
                                    html: '<?= $message['text']; ?>',
                                    confirmButtonText: 'OK'
                                });
                            });
                        </script>
                    <?php endif; ?>
                    
                    <form method="post" action="">
                        <div class="row">
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Current Password</label>
                                    <input required name="oldpass" type="password" id="oldpass" placeholder="Enter Current Password" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Enter New Password</label>
                                    <input required name="newpass" type="password" id="newpass" placeholder="Enter New Password" class="form-control">
                                </div>
                            </div>

                            <div class="col-sm-12 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Confirm New Password</label>
                                    <input required name="confpass" type="password" id="confpass" placeholder="Confirm New Password" class="form-control">
                                </div>
                            </div>
                        </div>
                        
                        <div class="pt-4">
                            <button type="submit" name="button" class="btn btn-primary">Update Password</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/vendor/choices/js/choices.min.js"></script>
<script src="assets/js/functions.js"></script>
</body>
</html>
