<?php
// File: reset_password.php
// Reset password after verification

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, User-Agent');

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

require_once 'config.php';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1');
define('ALLOWED_USER_AGENTS', [
    'Dart/',
    'ensi-flutter-app',
]);

// Helper: Validate API access
function validateApiAccess() {
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
    
    error_log("Password Reset API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

validateApiAccess();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Method not allowed', null, 405);
}

$input = getJsonInput();

// Validate input
if (empty($input['email']) || empty($input['code']) || empty($input['new_password'])) {
    sendResponse(false, 'Email, code, and new password are required');
}

$email = sanitizeInput($input['email']);
$code = sanitizeInput($input['code']);
$newPassword = $input['new_password']; // Don't sanitize password

// Validate email format
if (!validateEmail($email)) {
    sendResponse(false, 'Invalid email format');
}

// Validate code format
if (!preg_match('/^\d{4}$/', $code)) {
    sendResponse(false, 'Invalid code format');
}

// Validate new password
if (strlen($newPassword) < 6) {
    sendResponse(false, 'Password must be at least 6 characters');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Verify the code
    $stmt = $conn->prepare("
        SELECT id 
        FROM verification_codes 
        WHERE email = ? 
        AND code = ? 
        AND purpose = 'password_reset'
        AND is_used = 0 
        AND expires_at > NOW()
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$email, $code]);
    $verificationCode = $stmt->fetch();
    
    if (!$verificationCode) {
        logActivity("Invalid or expired password reset code for: $email");
        sendResponse(false, 'Invalid or expired verification code');
    }
    
    // Get user
    $stmt = $conn->prepare("SELECT id, is_deleted FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if (!$user) {
        sendResponse(false, 'User not found');
    }
    
    if ($user['is_deleted'] == 1) {
        sendResponse(false, 'This account has been deleted.');
    }
    
    // Hash new password
    $passwordHash = hashPassword($newPassword);
    
    // Update password
    $stmt = $conn->prepare("UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$passwordHash, $user['id']]);
    
    // Mark code as used
    $stmt = $conn->prepare("UPDATE verification_codes SET is_used = 1 WHERE id = ?");
    $stmt->execute([$verificationCode['id']]);
    
    logActivity("Password reset successfully for: $email");
    
    sendResponse(true, 'Password reset successfully. You can now login with your new password.');
    
} catch (Exception $e) {
    logActivity("Password reset error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
