<?php
// ==========================
// ERROR LOGGING
// ==========================
ini_set('display_errors', 0);  // don’t show errors to client
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php-error.log');

// ==========================
// CORS HANDLING (Allow All Origins)
// ==========================
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 1728000");
header('Content-Type: application/json');

// Handle preflight OPTIONS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// ==========================
// INCLUDES
// ==========================
require_once 'config.php';
include_once __DIR__ . '/unified_config.php'; // email system

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

if (!isset($input['email'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Email is required'
    ]);
    exit;
}

$email = trim($input['email']);
$new_password = $input['new_password'] ?? '';

// ==========================
// VALIDATE EMAIL
// ==========================
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid email format'
    ]);
    exit;
}

// Generate password if not provided
if (empty($new_password)) {
    $new_password = strtolower(substr($email, 0, 4)) . rand(1000, 9999);
}

// ==========================
// CHECK IF USER EXISTS
// ==========================
$stmt = $conn->prepare("SELECT id, first_name, last_name FROM loginusers WHERE email = ?");
if (!$stmt) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Prepare statement failed: ' . $conn->error
    ]);
    exit;
}
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user) {
    echo json_encode([
        'status' => 'error',
        'message' => 'No user found with this email'
    ]);
    exit;
}

// ==========================
// UPDATE PASSWORD
// ==========================
$stmt = $conn->prepare("UPDATE loginusers SET password = ? WHERE email = ?");
if (!$stmt) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Prepare statement failed: ' . $conn->error
    ]);
    exit;
}
$stmt->bind_param("ss", $new_password, $email);
if (!$stmt->execute()) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to update password: ' . $stmt->error
    ]);
    exit;
}
$stmt->close();

// ==========================
// SEND EMAIL
// ==========================
$emailSent = false;
if (defined('EMAIL_AUTOMATION_ENABLED') && EMAIL_AUTOMATION_ENABLED) {
    try {
        $mailSystem = getMailSystem();
        $fullName = trim($user['first_name'] . ' ' . $user['last_name']);
        
        $emailResult = $mailSystem->sendForgotPassword(
            $email,
            $fullName,
            $new_password
        );
        $emailSent = $emailResult['success'] ?? false;

        if (!$emailSent) {
            error_log("Forgot password email failed for $email: " . ($emailResult['message'] ?? 'Unknown error'));
        }
    } catch (Throwable $e) {
        error_log("Forgot password exception: " . $e->getMessage());
    }
}

// ==========================
// RESPONSE
// ==========================
echo json_encode([
    'status' => 'success',
    'message' => 'New password generated and emailed',
    'new_password' => $new_password, // ⚠ remove in production
    'email_sent' => $emailSent
]);

$conn->close();
?>
