<?php

class AddressController {

    // ─── GET /api/user/addresses ─────────────────────────────────────────────
    public static function getAddresses(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $db     = getDb();

        $stmt = $db->prepare(
            "SELECT id, address_type, full_name, phone, address, landmark, 
                    city, state, pincode, is_default, created_at, updated_at
             FROM addresses
             WHERE user_id = ?
             ORDER BY is_default DESC, created_at DESC"
        );
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $addresses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        sendSuccess($addresses);
    }

    // ─── POST /api/user/addresses/add ────────────────────────────────────────
    public static function addAddress(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $body   = getJsonBody();

        $type      = trim($body['address_type'] ?? 'home');
        $fullName  = trim($body['full_name'] ?? '');
        $phone     = trim($body['phone'] ?? '');
        $address   = trim($body['address'] ?? '');
        $landmark  = trim($body['landmark'] ?? '');
        $city      = trim($body['city'] ?? '');
        $state     = trim($body['state'] ?? '');
        $pincode   = trim($body['pincode'] ?? '');
        $isDefault = (bool)($body['is_default'] ?? false);

        if (!$fullName || !$phone || !$address || !$city || !$state || !$pincode) {
            sendError('All required fields must be filled', 422);
        }

        $db = getDb();

        // If this is the first address, make it default regardless
        $stmt = $db->prepare("SELECT COUNT(*) as count FROM addresses WHERE user_id = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $count = $stmt->get_result()->fetch_assoc()['count'];
        if ($count == 0) $isDefault = true;
        $stmt->close();

        if ($isDefault) {
            self::unsetDefaults($db, $userId);
        }

        $stmt = $db->prepare(
            "INSERT INTO addresses 
            (user_id, address_type, full_name, phone, address, landmark, city, state, pincode, is_default)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->bind_param(
            'issssssssi',
            $userId, $type, $fullName, $phone, $address, $landmark, $city, $state, $pincode, $isDefault
        );
        $stmt->execute();
        $newId = $stmt->insert_id;
        $stmt->close();

        sendSuccess(['id' => $newId], 'Address added successfully', 201);
    }

    // ─── PUT /api/user/addresses/update/{id} ───────────────────────────────
    public static function updateAddress(string $id): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $body   = getJsonBody();
        $addressId = (int)$id;

        $type      = trim($body['address_type'] ?? 'home');
        $fullName  = trim($body['full_name'] ?? '');
        $phone     = trim($body['phone'] ?? '');
        $address   = trim($body['address'] ?? '');
        $landmark  = trim($body['landmark'] ?? '');
        $city      = trim($body['city'] ?? '');
        $state     = trim($body['state'] ?? '');
        $pincode   = trim($body['pincode'] ?? '');
        $isDefault = (bool)($body['is_default'] ?? false);

        if (!$fullName || !$phone || !$address || !$city || !$state || !$pincode) {
            sendError('All required fields must be filled', 422);
        }

        $db = getDb();

        // Security check: belongs to user
        $stmt = $db->prepare("SELECT id FROM addresses WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $addressId, $userId);
        $stmt->execute();
        if (!$stmt->get_result()->fetch_assoc()) {
            $stmt->close();
            sendError('Address not found', 404);
        }
        $stmt->close();

        if ($isDefault) {
            self::unsetDefaults($db, $userId);
        }

        $stmt = $db->prepare(
            "UPDATE addresses 
             SET address_type = ?, full_name = ?, phone = ?, address = ?, 
                 landmark = ?, city = ?, state = ?, pincode = ?, is_default = ?
             WHERE id = ? AND user_id = ?"
        );
        $stmt->bind_param(
            'ssssssssiii',
            $type, $fullName, $phone, $address, $landmark, $city, $state, $pincode, $isDefault, $addressId, $userId
        );
        $stmt->execute();
        $stmt->close();

        sendSuccess(null, 'Address updated successfully');
    }

    // ─── DELETE /api/user/addresses/delete/{id} ─────────────────────────────
    public static function deleteAddress(string $id): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $addressId = (int)$id;

        $db = getDb();

        // 1. Check if the address being deleted is the default one
        $stmt = $db->prepare("SELECT is_default FROM addresses WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $addressId, $userId);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        $wasDefault = $res ? (bool)$res['is_default'] : false;
        $stmt->close();

        if (!$res) sendError('Address not found', 404);

        // 2. Perform deletion
        $stmt = $db->prepare("DELETE FROM addresses WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $addressId, $userId);
        $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();

        if (!$affected) sendError('Address not found', 404);

        // 3. If we deleted the default address, pick another one to be default
        if ($wasDefault) {
            // Find another address for the same user, pick the most recent
            $stmt = $db->prepare("SELECT id FROM addresses WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
            $stmt->bind_param('i', $userId);
            $stmt->execute();
            if ($newDefault = $stmt->get_result()->fetch_assoc()) {
                $stmt->close();
                $stmt = $db->prepare("UPDATE addresses SET is_default = 1 WHERE id = ?");
                $stmt->bind_param('i', $newDefault['id']);
                $stmt->execute();
            }
            $stmt->close();
        }

        sendSuccess(null, 'Address deleted successfully');
    }

    // ─── POST /api/user/addresses/set-default/{id} ──────────────────────────
    public static function setDefault(string $id): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $addressId = (int)$id;

        $db = getDb();

        // Check ownership
        $stmt = $db->prepare("SELECT id FROM addresses WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $addressId, $userId);
        $stmt->execute();
        if (!$stmt->get_result()->fetch_assoc()) {
            $stmt->close();
            sendError('Address not found', 404);
        }
        $stmt->close();

        self::unsetDefaults($db, $userId);

        $stmt = $db->prepare("UPDATE addresses SET is_default = 1 WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $addressId, $userId);
        $stmt->execute();
        $stmt->close();

        sendSuccess(null, 'Default address updated');
    }

    private static function unsetDefaults($db, $userId): void {
        $stmt = $db->prepare("UPDATE addresses SET is_default = 0 WHERE user_id = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $stmt->close();
    }
}
