<?php
require_once 'config.php';
require_once 'Database.php';
require_once '../helper_functions/data_request.php';

header('Content-Type: application/json');

$db = new Database();
$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (!preg_match('/Bearer\s+(.+)/', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized: No token']);
    exit;
}

$sessionId = $matches[1];

$session = fetchSingleDataWithJoins("
    SELECT user_id, user_type
    FROM mobile_sessions
    WHERE session_id = :session_id
      AND expires_at > NOW()
    LIMIT 1
", [':session_id' => $sessionId]);

if (!$session) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized: Invalid session']);
    exit;
}

$userId   = (int)$session['user_id'];
$userType = $session['user_type'];

function allowed_properties_list(int $userId, string $userType): array {
    switch ($userType) {
        case 'super_admin':
        case 'admin':
            return fetchDataWithJoins("SELECT id, name FROM properties ORDER BY id ASC", []);

        case 'dealer':
            return fetchDataWithJoins("
                SELECT p.id, p.name
                FROM organizations o
                JOIN properties p ON p.organization_id = o.id
                WHERE o.dealer_id = :uid
                ORDER BY p.id ASC
            ", [':uid' => $userId]);

        case 'organization_admin':
        case 'sub_dealer': {

            $byAccessId = fetchDataWithJoins("
                SELECT access_id AS pid
                FROM dealer_admins_access
                WHERE dealer_admin_id = :uid
                  AND access_type = 'property'
                  AND deleted_at IS NULL
            ", [':uid' => $userId]);

            $byPropCol  = fetchDataWithJoins("
                SELECT property_id AS pid
                FROM dealer_admins_access
                WHERE dealer_admin_id = :uid
                  AND property_id IS NOT NULL
                  AND deleted_at IS NULL
            ", [':uid' => $userId]);

            $ids = array_unique(array_filter(array_merge(
                array_column($byAccessId ?: [], 'pid'),
                array_column($byPropCol  ?: [], 'pid')
            ), 'is_numeric'));

            if (!$ids) return [];

            $ph = []; $pa = [];
            foreach ($ids as $i => $pid) { $k=":p$i"; $ph[]=$k; $pa[$k]=(int)$pid; }

            return fetchDataWithJoins("
                SELECT id, name
                FROM properties
                WHERE id IN (".implode(',', $ph).")
                ORDER BY id ASC
            ", $pa);
        }

        case 'dealer_admin':
            return fetchDataWithJoins("
                SELECT p.id, p.name
                FROM dealer_admins_access daa
                JOIN properties p ON p.id = daa.property_id
                WHERE daa.dealer_admin_id = :id
                ORDER BY p.id ASC
            ", [':id' => $userId]);

        case 'property_admin': {
            $row = fetchSingleDataWithJoins("
                SELECT property_id FROM users WHERE id = :id LIMIT 1
            ", [':id' => $userId]);
            if (!$row || empty($row['property_id'])) return [];
            return fetchDataWithJoins("
                SELECT id, name FROM properties WHERE id = :pid LIMIT 1
            ", [':pid' => (int)$row['property_id']]);
        }

        case 'property_user':
            return fetchDataWithJoins("
                SELECT p.id, p.name
                FROM properties p
                JOIN property_users pu ON pu.property_id = p.id
                WHERE pu.id = :id
                LIMIT 1
            ", [':id' => $userId]);

        case 'multi_prop': {
            $primary = fetchSingleDataWithJoins("
                SELECT p.id, p.name
                FROM property_users pu
                JOIN properties p ON pu.property_id = p.id
                WHERE pu.id = :id
                LIMIT 1
            ", [':id' => $userId]);

            $extra = fetchDataWithJoins("
                SELECT p.id, p.name
                FROM multi_prop_users mp
                JOIN properties p ON mp.property_id = p.id
                WHERE mp.user_assoc = :id
                  AND mp.deleted_at IS NULL
            ", [':id' => $userId]);

            return array_merge($primary ? [$primary] : [], $extra ?: []);
        }

        default:
            return [];
    }
}

function allowed_property_ids(int $userId, string $userType): array {
    $rows = allowed_properties_list($userId, $userType);
    return array_map(static fn($r) => (int)$r['id'], $rows ?: []);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $properties = allowed_properties_list($userId, $userType);
    echo json_encode($properties);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data       = json_decode(file_get_contents('php://input'), true);
    $propertyId = isset($data['property_id']) && is_numeric($data['property_id'])
        ? (int)$data['property_id'] : 0;

    if ($propertyId <= 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing or invalid property_id']);
        exit;
    }

    if ($userType === 'super_admin' || $userType === 'admin') {
        $exists = fetchSingleDataWithJoins("SELECT id FROM properties WHERE id = :id LIMIT 1", [':id' => $propertyId]);
        if (!$exists) {
            http_response_code(404);
            echo json_encode(['error' => 'Property not found']);
            exit;
        }
        updateTable('mobile_sessions', ['current_property_id' => $propertyId], 'session_id = :sid', ['sid' => $sessionId]);
        echo json_encode(['success' => true, 'new_property' => $propertyId]);
        exit;
    }

    $allowedIds = allowed_property_ids($userId, $userType);

    $valid = in_array($propertyId, $allowedIds, true);

    if (!$valid) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied to this property']);
        exit;
    }

    updateTable('mobile_sessions', ['current_property_id' => $propertyId], 'session_id = :sid', ['sid' => $sessionId]);
    echo json_encode(['success' => true, 'new_property' => $propertyId]);
    exit;
}

http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);