<?php
require_once('config.php');

// Regular request headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

// Read JSON input
$json = file_get_contents('php://input');
$data = json_decode($json, true);

$site_cd  = $data['site_cd'] ?? null;
$login_id = $data['login_id'] ?? null;

// Validate input
if (!$site_cd || !$login_id) {
    returnError("Missing required fields: site_cd or login_id");
    exit;
}

// Call stored procedure
$sql = "EXEC sp_cmms_reset_password ?, ?";
$params = [$site_cd, $login_id];

$stmt = sqlsrv_query($conn, $sql, $params);

	if ($stmt === false) {
        $errors = sqlsrv_errors();
        if (strpos($errors[0]['message'], 'Mail (Id:') !== false) {
            echo json_encode([
                'status' => 'SUCCESS',
                'message' => 'Password reset successful! Check your email.'
            ]);
            exit();
        }
        returnError("Database error: " . $errors[0]['message']);
    }
    
    echo json_encode([
        'status' => 'SUCCESS',
        'message' => 'Password reset successfully. Check your email.'
    ]);
    
    sqlsrv_free_stmt($stmt);

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
returnData();


// ✅ Success Response
function returnData() {
    $returnData = array(
        'status' => 'SUCCESS',
        'message' => 'Password reset successful, email sent'
    );
    echo json_encode($returnData);
    exit;
}

// ❌ Error Response
function returnError($error_message, $sql_errors = null) {
    $returnData = array(
        'status' => 'ERROR',
        'message' => $error_message,
    );

    if ($sql_errors) {
        $returnData['sql_errors'] = $sql_errors;
    }

    echo json_encode($returnData);
    exit;
}
?>