<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once 'config.php'; // Database connection

$response = ["success" => false, "message" => "Invalid request"];

$data = json_decode(file_get_contents("php://input"));

// Check if JSON decoded properly
if (!$data) {
    echo json_encode(["success" => false, "message" => "Invalid JSON input"]);
    exit;
}

// Check required fields
if (isset($data->email, $data->current_password, $data->new_password, $data->confirm_new_password)) {
    $email = $conn->real_escape_string($data->email);
    $current_password = $conn->real_escape_string($data->current_password);
    $new_password = $conn->real_escape_string($data->new_password);
    $confirm_new_password = $conn->real_escape_string($data->confirm_new_password);

    if ($new_password !== $confirm_new_password) {
        echo json_encode(["success" => false, "message" => "New password and confirm password do not match"]);
        exit;
    }

    // Check if user exists in adminlogins
    $sql = "SELECT password FROM adminlogins WHERE email='$email' LIMIT 1";
    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $user = $result->fetch_assoc();

        if ($user['password'] === $current_password) {
            $update = $conn->query("UPDATE adminlogins SET password='$new_password' WHERE email='$email'");
            if ($update) {
                $response = ["success" => true, "message" => "Password updated successfully"];
            } else {
                $response = ["success" => false, "message" => "Failed to update password"];
            }
        } else {
            $response = ["success" => false, "message" => "Current password is incorrect"];
        }
    } else {
        $response = ["success" => false, "message" => "Admin not found"];
    }
} else {
    $response = ["success" => false, "message" => "All fields are required"];
}

echo json_encode($response);
