<?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 __DIR__ . '/../unified_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) {
                // ------------------
                // Send password change notification email
                // ------------------
                $emailSent = false;
                if (EMAIL_AUTOMATION_ENABLED) {
                    // Get admin details for email
                    $adminStmt = $conn->query("SELECT first_name, last_name FROM adminlogins WHERE email='$email' LIMIT 1");
                    if ($adminStmt && $adminStmt->num_rows > 0) {
                        $adminDetails = $adminStmt->fetch_assoc();
                        $fullName = trim($adminDetails['first_name'] . ' ' . $adminDetails['last_name']);
                        
                        $mailSystem = getMailSystem();
                        $emailResult = $mailSystem->sendPasswordChanged(
                            $email, 
                            $fullName, 
                            $_SERVER['REMOTE_ADDR'] ?? 'Unknown'
                        );
                        
                        $emailSent = $emailResult['success'];
                        
                        // Log email result
                        if (!$emailResult['success']) {
                            error_log("Failed to send password change email to $email: " . $emailResult['message']);
                        }
                    }
                }
                
                $response = [
                    "success" => true, 
                    "message" => "Password updated successfully",
                    "email_sent" => $emailSent
                ];
            } 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);
