<?php
session_start();
require_once(__DIR__ . "/../config/db.php");
require_once(__DIR__ . "/../session.php");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $csrf_token = $_POST['csrf_token'] ?? '';
    if ($csrf_token !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token CSRF tidak valid.";
        header("Location: /");
        exit();
    }

    $old_password = $_POST['OldPassword'];
    $new_password = $_POST['NewPassword'];
    $confirm_password = $_POST['ConfirmPassword'];

    if ($new_password != $confirm_password) {
        $_SESSION['error'] = "Kata sandi baru dan konfirmasi kata sandi tidak cocok.";
        header("Location: /");
        exit();
    }

    if (!preg_match('/^(?=.{8,20}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*$/', $new_password)) {
        $_SESSION['error'] = "Kata sandi baru tidak memenuhi syarat.";
        header("Location: /");
        exit();
    }

    $query = "SELECT password FROM user WHERE id = :user_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($old_password, $user['password'])) {
        $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        $query = "UPDATE user SET password = :password WHERE id = :user_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':password', $new_hashed_password, PDO::PARAM_STR);
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);

        if ($stmt->execute()) {
            $_SESSION['message'] = "Password berhasil diubah";
            header("Location: /");
            exit();
        } else {
            $_SESSION['error'] = "Terjadi kesalahan. Silakan coba lagi.";
            header("Location: /");
            exit();
        }
    } else {
        $_SESSION['error'] = "Kata sandi saat ini salah.";
        header("Location: /");
        exit();
    }
}
