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

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

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Log the start of the request
error_log("=== CHANGE PASSWORD API CALL START ===");
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Request URI: " . $_SERVER['REQUEST_URI']);
error_log("Raw Input: " . file_get_contents('php://input'));

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

try {
    // Get JSON input
    $rawInput = file_get_contents('php://input');
    error_log("Raw input received: " . $rawInput);
    
    $input = json_decode($rawInput, true);
    error_log("Decoded input: " . json_encode($input));
    
    if (!$input) {
        error_log("JSON decode failed");
        sendError('Invalid JSON input');
    }
    
                    $token = $input['token'] ?? '';
                $newPassword = $input['new_password'] ?? '';
                $confirmPassword = $input['confirm_password'] ?? '';
                
                // Validate required fields
                if (empty($token) || empty($newPassword) || empty($confirmPassword)) {
                    sendError('All fields are required');
                }
                
                // Validate password confirmation
                if ($newPassword !== $confirmPassword) {
                    sendError('New password and confirmation do not match');
                }
                
                // Validate new password length
                if (strlen($newPassword) < 6) {
                    sendError('New password must be at least 6 characters long');
                }
                
                // Verify token and get user
                error_log("Attempting to verify token: " . substr($token, 0, 20) . "...");
                $userId = verifyToken($token);
                error_log("Token verification result: " . ($userId ? "SUCCESS - User ID: $userId" : "FAILED"));
                
                if (!$userId) {
                    error_log("Token verification failed");
                    sendError('Invalid or expired token');
                }
                
                // Check if user exists
                error_log("Checking if user exists for ID: $userId");
                $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                error_log("User check result: " . ($user ? "SUCCESS" : "FAILED"));
                
                if (!$user) {
                    error_log("User not found in database");
                    sendError('User not found');
                }
    
    // Hash new password
    error_log("Hashing new password...");
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    error_log("Password hashed successfully");
    
    // Update password in database
    error_log("Updating password in database...");
    $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
    $updateResult = $stmt->execute([$hashedPassword, $userId]);
    error_log("Update query executed. Result: " . ($updateResult ? "SUCCESS" : "FAILED"));
    error_log("Rows affected: " . $stmt->rowCount());
    
    if ($stmt->rowCount() > 0) {
        error_log("Password update successful");
        echo json_encode([
            'success' => true,
            'message' => 'Password changed successfully',
            'data' => [
                'success' => true,
                'message' => 'Password changed successfully'
            ]
        ]);
    } else {
        error_log("Password update failed - no rows affected");
        sendError('Failed to update password');
    }
    
} catch (Exception $e) {
    error_log("Change password error: " . $e->getMessage());
    sendError('Internal server error');
}
?>
