<?php
// Error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Files ko include karna
require_once '../config/cors.php';
require_once '../config/database.php';

// Database connection Class se banaya gaya hai
$database = new Database();
$db = $database->getConnection(); // Is connection ($db) ka istemal karenge

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

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

// URL se User ID lena
$userId = $_GET['userId'] ?? null;
if (!$userId) {
    http_response_code(400);
    echo json_encode(['error' => 'User ID is missing in the URL']);
    exit;
}

try {
    // Request body se data lena
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON input']);
        exit;
    }

    $updateFields = [];
    $params = [];
    
    // Update kiye jaane wale allowed fields
    $allowedFields = [
        'first_name', 'last_name', 'name', 'email', 'phone', 
        'date_of_birth', 'gender', 'profile_image', 'bio'
    ];
    
    foreach ($allowedFields as $field) {
        if (isset($input[$field])) {
            $updateFields[] = "$field = :$field";
            $params[$field] = $input[$field];
        }
    }
    
    // Password update ka logic
    if (isset($input['password']) && !empty($input['password'])) {
        if (isset($input['current_password'])) {
            // Purana password check karna
            $stmt = $db->prepare("SELECT password_hash FROM users WHERE id = :user_id");
            $stmt->execute(['user_id' => $userId]);
            $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$currentUser || !password_verify($input['current_password'], $currentUser['password_hash'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Current password is incorrect']);
                exit;
            }
        }
        
        $updateFields[] = "password_hash = :password_hash";
        $params['password_hash'] = password_hash($input['password'], PASSWORD_DEFAULT);
    }
    
    if (empty($updateFields)) {
        http_response_code(400);
        echo json_encode(['error' => 'No valid fields to update']);
        exit;
    }
    
    $updateFields[] = "updated_at = CURRENT_TIMESTAMP";
    $params['user_id'] = $userId;
    
    // Update query execute karna
    $sql = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :user_id";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    
    // Update hua data wapas bhejna
    $stmt = $db->prepare("
        SELECT id, first_name, last_name, name, email, phone, date_of_birth, 
               gender, profile_image, bio, role, email_verified, is_active, 
               created_at, updated_at 
        FROM users 
        WHERE id = :user_id
    ");
    $stmt->execute(['user_id' => $userId]);
    $updatedUser = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'message' => 'Profile updated successfully',
        'user' => $updatedUser
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'An error occurred: ' . $e->getMessage()]);
}
?>