<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Remove BOM and ensure proper encoding
ob_clean();
header('Cache-Control: no-cache, must-revalidate');

require_once '../config/database.php';

try {
    // Get database connection
    $pdo = getDBConnection();
    
    // Get input data
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    $mobile = trim($input['mobile'] ?? '');
    $newPassword = trim($input['new_password'] ?? '');
    
    // Validate input
    if (empty($mobile)) {
        throw new Exception('Mobile number is required');
    }
    
    if (empty($newPassword)) {
        throw new Exception('New password is required');
    }
    
    if (strlen($newPassword) < 6) {
        throw new Exception('Password must be at least 6 characters long');
    }
    
    if (!preg_match('/^[0-9]{10}$/', $mobile)) {
        throw new Exception('Invalid mobile number format');
    }
    
    // Check if user exists
    $checkUser = $pdo->prepare("SELECT id FROM users WHERE mobile = ?");
    $checkUser->execute([$mobile]);
    
    if ($checkUser->rowCount() == 0) {
        throw new Exception('User not found with this mobile number');
    }
    
    // Hash the new password
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    
    // Update password
    // Check if updated_at column exists
    $updatedAtExistsStmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'updated_at'");
    $updatedAtExists = $updatedAtExistsStmt && $updatedAtExistsStmt->rowCount() > 0;

    $updateQuery = $updatedAtExists
        ? "UPDATE users SET password = ?, updated_at = NOW() WHERE mobile = ?"
        : "UPDATE users SET password = ? WHERE mobile = ?";

    $updatePassword = $pdo->prepare($updateQuery);
    $result = $updatePassword->execute([$hashedPassword, $mobile]);
    
    if (!$result) {
        throw new Exception('Failed to update password');
    }
    
    // Log the password reset
    error_log("Password reset successful for mobile: $mobile");
    
    echo json_encode([
        'success' => true,
        'message' => 'Password reset successfully',
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    error_log("Password reset error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
}
?>
