<?php

// Handle CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

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

// Initialize DB
/** @var PDO $pdo */
$pdo = require __DIR__ . '/db.php';

// Helper to send JSON response
function sendJsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit();
}

$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Serve the Web UI directly from ../web/dist if it's not an API request
if (strpos($requestUri, '/api/') !== 0 && $requestUri !== '/api') {
    $filePath = realpath(__DIR__ . '/../web/dist' . $requestUri);
    
    // Default to index.html for root path or React Router paths
    if (!$filePath || !is_file($filePath)) {
        $filePath = realpath(__DIR__ . '/../web/dist/index.html');
    }

    if ($filePath && is_file($filePath)) {
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        $mimeTypes = [
            'html' => 'text/html',
            'css'  => 'text/css',
            'js'   => 'application/javascript',
            'svg'  => 'image/svg+xml',
            'png'  => 'image/png',
            'ico'  => 'image/x-icon'
        ];
        
        if (isset($mimeTypes[$ext])) {
            header('Content-Type: ' . $mimeTypes[$ext]);
        }
        readfile($filePath);
        exit();
    }
}
$method = $_SERVER['REQUEST_METHOD'];
$validToken = "xavisoft_auth_T9j2K8xN4qR7";
$hardcodedPassword = "admin"; // Hardcoded UI password

if ($requestUri === '/api/login' && $method === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if (($data['password'] ?? '') === $hardcodedPassword) {
        sendJsonResponse(['token' => $validToken]);
    } else {
        sendJsonResponse(['error' => 'Invalid password'], 401);
    }
}

// API Key Authentication (Skip for login)
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? '';

if ($authHeader !== "Bearer $validToken") {
    sendJsonResponse(['error' => 'Unauthorized'], 401);
}

if ($requestUri === '/api/sync' && $method === 'POST') {
    // Sync notifications and call logs
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (!$data) {
        sendJsonResponse(['error' => 'Invalid JSON'], 400);
    }

    try {
        $pdo->beginTransaction();

        // Process Notifications
        if (isset($data['notifications']) && is_array($data['notifications'])) {
            $stmt = $pdo->prepare("INSERT INTO notifications (app_package, title, text, created_at) VALUES (?, ?, ?, ?)");
            foreach ($data['notifications'] as $notif) {
                $stmt->execute([
                    $notif['app_package'] ?? 'unknown',
                    $notif['title'] ?? '',
                    $notif['text'] ?? '',
                    $notif['created_at'] ?? time()
                ]);
            }
        }

        // Process Call Logs
        if (isset($data['call_logs']) && is_array($data['call_logs'])) {
            $stmt = $pdo->prepare("INSERT OR IGNORE INTO call_logs (call_type, duration, name, phone_number, created_at) VALUES (?, ?, ?, ?, ?)");
            foreach ($data['call_logs'] as $call) {
                $stmt->execute([
                    $call['call_type'] ?? 'unknown',
                    $call['duration'] ?? 0,
                    $call['name'] ?? '',
                    $call['phone_number'] ?? '',
                    $call['created_at'] ?? time()
                ]);
            }
        }

        $pdo->commit();
        sendJsonResponse(['success' => true]);

    } catch (Exception $e) {
        $pdo->rollBack();
        sendJsonResponse(['error' => $e->getMessage()], 500);
    }
} elseif ($requestUri === '/api/notifications' && $method === 'GET') {
    // Fetch notifications
    $appFilter = $_GET['app'] ?? null;
    $cursor = isset($_GET['cursor']) ? (int)$_GET['cursor'] : null;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $isStarred = isset($_GET['starred']) && $_GET['starred'] === '1';
    
    $query = "SELECT * FROM notifications";
    $countQuery = "SELECT COUNT(*) FROM notifications";
    $params = [];
    $countParams = [];
    
    $conditions = [];
    
    if ($appFilter) {
        $conditions[] = "app_package = ?";
        $params[] = $appFilter;
        $countParams[] = $appFilter;
    }
    
    if ($isStarred) {
        $conditions[] = "is_starred = 1";
    }
    
    if ($cursor) {
        $conditions[] = "id < ?";
        $params[] = $cursor;
    }
    
    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
        
        $countConditions = [];
        if ($appFilter) $countConditions[] = "app_package = ?";
        if ($isStarred) $countConditions[] = "is_starred = 1";
        if (!empty($countConditions)) {
            $countQuery .= " WHERE " . implode(" AND ", $countConditions);
        }
    }
    
    $query .= " ORDER BY id DESC LIMIT ?";
    $params[] = $limit;
    
    // Get total count
    $stmtCount = $pdo->prepare($countQuery);
    $stmtCount->execute($countParams);
    $total = $stmtCount->fetchColumn();
    
    // Get data
    $stmt = $pdo->prepare($query);
    foreach ($params as $index => $value) {
        $type = is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR;
        $stmt->bindValue($index + 1, $value, $type);
    }
    
    $stmt->execute();
    $notifications = $stmt->fetchAll();
    foreach ($notifications as &$n) {
        $n['id'] = (int)$n['id'];
        $n['created_at'] = (int)$n['created_at'];
        $n['is_starred'] = (bool)$n['is_starred'];
    }
    
    $nextCursor = null;
    if (count($notifications) > 0) {
        $lastItem = end($notifications);
        $nextCursor = $lastItem['id'];
        
        // Check if there are more items after this cursor
        $moreQuery = "SELECT 1 FROM notifications";
        $moreConditions = ["id < ?"];
        $moreParams = [$nextCursor];
        if ($appFilter) {
            $moreConditions[] = "app_package = ?";
            $moreParams[] = $appFilter;
        }
        if ($isStarred) {
            $moreConditions[] = "is_starred = 1";
        }
        $moreQuery .= " WHERE " . implode(" AND ", $moreConditions) . " LIMIT 1";
        $moreStmt = $pdo->prepare($moreQuery);
        $moreStmt->execute($moreParams);
        if (!$moreStmt->fetchColumn()) {
            $nextCursor = null;
        }
    }
    
    sendJsonResponse([
        'data' => $notifications,
        'pagination' => [
            'total' => $total,
            'limit' => $limit,
            'next_cursor' => $nextCursor
        ]
    ]);
} elseif ($requestUri === '/api/call-logs' && $method === 'GET') {
    // Fetch call logs
    $cursor = isset($_GET['cursor']) ? (int)$_GET['cursor'] : null;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $isStarred = isset($_GET['starred']) && $_GET['starred'] === '1';

    $query = "SELECT * FROM call_logs";
    $countQuery = "SELECT COUNT(*) FROM call_logs";
    $params = [];

    $conditions = [];

    if ($isStarred) {
        $conditions[] = "is_starred = 1";
    }

    if ($cursor) {
        $conditions[] = "id < ?";
        $params[] = $cursor;
    }

    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
        if ($isStarred) {
            $countQuery .= " WHERE is_starred = 1";
        }
    }

    $query .= " ORDER BY id DESC LIMIT ?";
    $params[] = $limit;

    // Get total count
    $stmtCount = $pdo->query($countQuery);
    $total = $stmtCount->fetchColumn();

    // Get data
    $stmt = $pdo->prepare($query);
    foreach ($params as $index => $value) {
        $type = is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR;
        $stmt->bindValue($index + 1, $value, $type);
    }

    $stmt->execute();
    $callLogs = $stmt->fetchAll();
    foreach ($callLogs as &$c) {
        $c['id'] = (int)$c['id'];
        $c['duration'] = (int)$c['duration'];
        $c['created_at'] = (int)$c['created_at'];
        $c['is_starred'] = (bool)$c['is_starred'];
    }

    $nextCursor = null;
    if (count($callLogs) > 0) {
        $lastItem = end($callLogs);
        $nextCursor = $lastItem['id'];

        // Check if there are more items after this cursor
        $moreQuery = "SELECT 1 FROM call_logs WHERE id < ?";
        if ($isStarred) {
            $moreQuery .= " AND is_starred = 1";
        }
        $moreQuery .= " LIMIT 1";
        $moreStmt = $pdo->prepare($moreQuery);
        $moreStmt->execute([$nextCursor]);
        if (!$moreStmt->fetchColumn()) {
            $nextCursor = null;
        }
    }

    sendJsonResponse([
        'data' => $callLogs,
        'pagination' => [
            'total' => $total,
            'limit' => $limit,
            'next_cursor' => $nextCursor
        ]
    ]);
} elseif (preg_match('#^/api/(notifications|call-logs)/(\d+)/is_starred$#', $requestUri, $matches) && $method === 'PUT') {
    $entity = $matches[1];
    $id = (int)$matches[2];
    
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (!isset($data['is_starred'])) {
        sendJsonResponse(['error' => 'Missing is_starred boolean'], 400);
    }
    
    $isStarred = $data['is_starred'] ? 1 : 0;
    $table = $entity === 'notifications' ? 'notifications' : 'call_logs';
    
    $stmt = $pdo->prepare("UPDATE $table SET is_starred = ? WHERE id = ?");
    $stmt->execute([$isStarred, $id]);
    
    sendJsonResponse(['success' => true]);
} else {
    // Not found
    sendJsonResponse(['error' => 'Endpoint not found'], 404);
}
