<?php
require_once __DIR__ . '/includes/admin_auth.php';
require_once __DIR__ . '/includes/db.php'; // This file should initialize the $db = new mysqli(...) connection

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error'] = "Invalid request method";
    header("Location: profile.php");
    exit();
}

// Get form data
$currentPassword = trim($_POST['current_password']);
$newPassword = trim($_POST['new_password']);
$confirmPassword = trim($_POST['confirm_password']);

// Validate data
if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
    $_SESSION['error'] = "All fields are required";
    header("Location: profile.php");
    exit();
}

if ($newPassword !== $confirmPassword) {
    $_SESSION['error'] = "New passwords do not match";
    header("Location: profile.php");
    exit();
}

// Verify current password
$stmt = $db->prepare("SELECT password_hash FROM admin_users WHERE id = ?");
$stmt->bind_param("i", $_SESSION['admin_id']);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user || !password_verify($currentPassword, $user['password_hash'])) {
    $_SESSION['error'] = "Current password is incorrect";
    header("Location: profile.php");
    exit();
}

// Update password
$passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);

$stmt = $db->prepare("UPDATE admin_users SET password_hash = ? WHERE id = ?");
$stmt->bind_param("si", $passwordHash, $_SESSION['admin_id']);

if ($stmt->execute()) {
    $_SESSION['success'] = "Password changed successfully";
} else {
    $_SESSION['error'] = "Database error: " . $stmt->error;
}

$stmt->close();
header("Location: profile.php");
exit();
?>
