<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$user = $auth->requireAuth();
$db = new Database();
$pdo = $db->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        $stmt = $db->query("SELECT * FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC", [$user['id']]);
        $addresses = $stmt->fetchAll(PDO::FETCH_ASSOC);
        jsonResponse(['success' => true, 'addresses' => $addresses]);

    } elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        $label = trim($input['label'] ?? '');
        $address = trim($input['address'] ?? '');
        $is_default = isset($input['is_default']) ? (bool)$input['is_default'] : false;
        $address_id = $input['id'] ?? null;

        if (empty($label) || empty($address)) {
            throw new Exception("Label and address are required.");
        }

        $pdo->beginTransaction();

        // If setting this as default, unset other defaults first
        if ($is_default) {
            $db->query("UPDATE user_addresses SET is_default = FALSE WHERE user_id = ?", [$user['id']]);
        }

        if ($address_id) {
            // Update existing address
            $db->query(
                "UPDATE user_addresses SET label = ?, address = ?, is_default = ? WHERE id = ? AND user_id = ?",
                [$label, $address, $is_default, $address_id, $user['id']]
            );
            $message = 'Address updated successfully.';
        } else {
            // Create new address
            $db->query(
                "INSERT INTO user_addresses (user_id, label, address, is_default) VALUES (?, ?, ?, ?)",
                [$user['id'], $label, $address, $is_default]
            );
            $message = 'Address added successfully.';
        }

        $pdo->commit();
        jsonResponse(['success' => true, 'message' => $message]);

    } elseif ($method === 'DELETE') {
        $input = json_decode(file_get_contents('php://input'), true);
        $address_id = $input['id'] ?? null;

        if (!$address_id) {
            throw new Exception("Address ID is required for deletion.");
        }

        $stmt = $db->query("DELETE FROM user_addresses WHERE id = ? AND user_id = ?", [$address_id, $user['id']]);

        if ($stmt->rowCount() > 0) {
            jsonResponse(['success' => true, 'message' => 'Address deleted successfully.']);
        } else {
            throw new Exception("Address not found or you do not have permission to delete it.");
        }

    } else {
        jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>