<?php
// ══════════════════════════════════════════════════
// EPD — Admin Change Password API
// File: /backend/api/admin-change-password.php
// ══════════════════════════════════════════════════
error_reporting(0);
ini_set('display_errors', 0);
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;
}

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

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

$username     = trim($input['username']         ?? '');
$old_password = trim($input['old_password']     ?? '');
$new_password = trim($input['new_password']     ?? '');
$confirm      = trim($input['confirm_password'] ?? '');

// ── Validation ──
if (!$username || !$old_password || !$new_password || !$confirm) {
    echo json_encode(['status' => 'error', 'message' => 'Sab fields required hain']);
    exit;
}
if ($new_password !== $confirm) {
    echo json_encode(['status' => 'error', 'message' => 'New passwords match nahi karte']);
    exit;
}
if (strlen($new_password) < 6) {
    echo json_encode(['status' => 'error', 'message' => 'Min 6 characters required']);
    exit;
}

// ── DB se current password check karo ──
$row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT id, password FROM admin WHERE username = '" . mysqli_real_escape_string($conn, $username) . "' LIMIT 1"
));

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

// ── Plain text ya hashed dono support ──
$isValid = false;
if (password_verify($old_password, $row['password'])) {
    $isValid = true; // bcrypt hashed
} elseif ($row['password'] === $old_password) {
    $isValid = true; // plain text (purana)
}

if (!$isValid) {
    echo json_encode(['status' => 'error', 'message' => 'Current password galat hai']);
    exit;
}

// ── Nayi password hash karke save karo ──
$hashed =$new_password;
$update = mysqli_query($conn,
    "UPDATE admin SET password = '" . mysqli_real_escape_string($conn, $hashed) . "' WHERE username = '" . mysqli_real_escape_string($conn, $username) . "'"
);

if ($update) {
    echo json_encode(['status' => 'success', 'message' => 'Password successfully updated!']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'DB update failed: ' . mysqli_error($conn)]);
}