<?php
require_once 'config/config.php';
session_start();

$lang_code = $_SESSION['language'] ?? 'english';
require_once "languages/$lang_code.php";

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'];
    $new_password     = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($hashed_password);
    $stmt->fetch();
    $stmt->close();

    if (!password_verify($current_password, $hashed_password)) {
        $message = "<div class='alert alert-danger'>{$lang['incorrect_current_password']}</div>";
    } elseif ($new_password !== $confirm_password) {
        $message = "<div class='alert alert-danger'>{$lang['passwords_not_match']}</div>";
    } else {
        $new_hashed = password_hash($new_password, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->bind_param("si", $new_hashed, $user_id);
        $stmt->execute();
        $message = "<div class='alert alert-success'>{$lang['password_changed_successfully']}</div>";
    }
}
?>

<?php include 'header.php'; ?>

<div class="main-content p-4" style="flex: 1;">
    <h3><?= $lang['change_password'] ?></h3>
    <?= $message ?>
    <form method="POST" class="mt-3">
        <div class="mb-3">
            <label class="form-label"><?= $lang['current_password'] ?></label>
            <input type="password" name="current_password" class="form-control" required>
        </div>
        <div class="mb-3">
            <label class="form-label"><?= $lang['new_password'] ?></label>
            <input type="password" name="new_password" class="form-control" required>
        </div>
        <div class="mb-3">
            <label class="form-label"><?= $lang['confirm_password'] ?></label>
            <input type="password" name="confirm_password" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-primary"><?= $lang['update'] ?></button>
    </form>
</div>

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