<?php

// ════════════════════════════════════════════════════════

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'POST only']);
    exit;
}

require_once '../config/db.php';

$body = json_decode(file_get_contents('php://input'), true);

$username    = trim($body['username']    ?? '');
$old_pass    = trim($body['old_password'] ?? '');
$new_pass    = trim($body['new_password'] ?? '');
$confirm     = trim($body['confirm_password'] ?? '');

// ── Validation ──
if (!$username || !$old_pass || !$new_pass || !$confirm) {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
    exit;
}
if ($new_pass !== $confirm) {
    echo json_encode(['status' => 'error', 'message' => 'New passwords do not match.']);
    exit;
}
if (strlen($new_pass) < 6) {
    echo json_encode(['status' => 'error', 'message' => 'Password must be at least 6 characters.']);
    exit;
}

try {
    // ── Fetch admin record ──
    $stmt = $pdo->prepare("SELECT * FROM admin WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        echo json_encode(['status' => 'error', 'message' => 'Admin username not found.']);
        exit;
    }

    // ── Verify current password ──
    // Supports both: plain text (legacy) AND password_hash
    $passOk = false;
    if (password_verify($old_pass, $admin['password'])) {
        $passOk = true;                          // hashed match
    } elseif ($admin['password'] === $old_pass) {
        $passOk = true;                          // plain text match (legacy)
    }

    if (!$passOk) {
        echo json_encode(['status' => 'error', 'message' => 'Current password is incorrect.']);
        exit;
    }

    // ── Update with hashed new password ──
    $hashed = password_hash($new_pass, PASSWORD_DEFAULT);
    $upd = $pdo->prepare("UPDATE admin SET password = ? WHERE username = ?");
    $upd->execute([$hashed, $username]);

    echo json_encode(['status' => 'success', 'message' => 'Password changed successfully!']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}