<?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
$database = new Database();
$db = $database->getConnection();

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

// 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 {
    switch ($_SERVER['REQUEST_METHOD']) {
        case 'GET':
            // ... GET code theek hai ...
            $stmt = $db->prepare("
                SELECT id, label, address_line1, address_line2, city, state, postal_code, country, is_default
                FROM addresses WHERE user_id = :user_id ORDER BY is_default DESC, created_at DESC
            ");
            $stmt->execute(['user_id' => $userId]);
            $addresses = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'addresses' => $addresses]);
            break;
            
        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            // ... validation ...
            
            if (isset($input['is_default']) && $input['is_default']) {
                $stmt = $db->prepare("UPDATE addresses SET is_default = FALSE WHERE user_id = :user_id");
                $stmt->execute(['user_id' => $userId]);
            }
            
            // --- YAHAN FIX KIYA GAYA HAI ---
            // 'is_default' ki value ko hamesha 1 ya 0 mein convert karein
            $isDefaultValue = isset($input['is_default']) ? (int)(bool)$input['is_default'] : 0;
            
            $stmt = $db->prepare("
                INSERT INTO addresses (user_id, label, address_line1, address_line2, city, state, postal_code, country, is_default) 
                VALUES (:user_id, :label, :address_line1, :address_line2, :city, :state, :postal_code, :country, :is_default)
            ");
            $stmt->execute([
                'user_id' => $userId,
                'label' => $input['label'],
                'address_line1' => $input['address_line1'],
                'address_line2' => $input['address_line2'] ?? null,
                'city' => $input['city'],
                'state' => $input['state'],
                'postal_code' => $input['postal_code'],
                'country' => $input['country'] ?? 'India',
                'is_default' => $isDefaultValue // Theek ki hui value ka istemal
            ]);
            echo json_encode(['success' => true, 'message' => 'Address added', 'address_id' => $db->lastInsertId()]);
            break;
            
        case 'PUT':
            $input = json_decode(file_get_contents('php://input'), true);
            // ... validation ...

            if (isset($input['is_default']) && $input['is_default']) {
                $stmt = $db->prepare("UPDATE addresses SET is_default = FALSE WHERE user_id = :user_id");
                $stmt->execute(['user_id' => $userId]);
            }
            
            $updateFields = [];
            $params = ['id' => $input['id'], 'user_id' => $userId];
            $allowedFields = ['label', 'address_line1', 'address_line2', 'city', 'state', 'postal_code', 'country', 'is_default'];
            
            foreach ($allowedFields as $field) {
                if (isset($input[$field])) {
                    $updateFields[] = "$field = :$field";
                    
                    // --- YAHAN BHI FIX KIYA GAYA HAI ---
                    // Update ke liye bhi 'is_default' ko 1 ya 0 mein convert karein
                    if ($field === 'is_default') {
                        $params[$field] = (int)(bool)$input[$field];
                    } else {
                        $params[$field] = $input[$field];
                    }
                }
            }
            
            if (!empty($updateFields)) {
                $sql = "UPDATE addresses SET " . implode(', ', $updateFields) . " WHERE id = :id AND user_id = :user_id";
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
            }
            
            echo json_encode(['success' => true, 'message' => 'Address updated']);
            break;
            
        case 'DELETE':
            // ... DELETE code theek hai ...
            $addressId = $_GET['id'] ?? null;
            if (!$addressId) {
                http_response_code(400);
                echo json_encode(['error' => 'Address ID (`id`) is required in the URL parameters']);
                exit;
            }
            
            $stmt = $db->prepare("DELETE FROM addresses WHERE id = :id AND user_id = :user_id");
            $stmt->execute(['id' => $addressId, 'user_id' => $userId]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Address deleted successfully']);
            } else {
                http_response_code(404);
                echo json_encode(['error' => 'Address not found or does not belong to this user']);
            }
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }

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