<?php
require_once('db.php');
session_start();

// Make sure the user is logged in
if (!isset($_SESSION['emp_id'])) {
    header("Location: login.php");
    exit();
}

// Process form
// Process form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $emp_id = $_SESSION['emp_id'];
    $old_password = md5($_POST['old_password']);
    $new_password = md5($_POST['new_password']);
    $confirm_password = md5($_POST['confirm_password']);

    if ($new_password !== $confirm_password) {
        $error = "رمز عبور جدید با تکرار آن مطابقت ندارد.";
    } else {
        // Get current password from DB
        $stmt = $conn->prepare("SELECT emp_password FROM employee WHERE emp_id = ?");
        $stmt->execute([$emp_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($result && $result['emp_password'] === $old_password) {
            // Update the password
            $update = $conn->prepare("UPDATE employee SET emp_password = ? WHERE emp_id = ?");
            if ($update->execute([$new_password, $emp_id])) {
                // Redirect to index page after success
                header("Location: index.php");
                exit(); // Always call exit after header redirect
            } else {
                $error = "خطا در تغییر رمز عبور.";
            }
        } else {
            $error = "رمز عبور فعلی نادرست است.";
        }
    }
}

?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>تغییر رمز عبور</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css">
</head>
<body class="bg-light">
<div class="container mt-5">
    <div class="card mx-auto shadow" style="max-width: 400px;">
        <div class="card-body">
            <h5 class="card-title text-center">تغییر رمز عبور</h5>

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

            <form method="POST">
                <div class="mb-3">
                    <label class="form-label">رمز عبور فعلی</label>
                    <input type="password" name="old_password" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">رمز عبور جدید</label>
                    <input type="password" name="new_password" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">تکرار رمز عبور جدید</label>
                    <input type="password" name="confirm_password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary w-100">ذخیره تغییرات</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>
