<?php
// public/parse.php

// =======================================================================
// 1. EXTENSION CONNECTION HEADERS (MUST BE AT THE VERY TOP)
// =======================================================================
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// Handle "Preflight" OPTIONS request from Chrome
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
// =======================================================================

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/auth.php';
require_once __DIR__ . '/../src/parser.php';

// 2. GET DATA (File, Post Text, or Raw Input)
$content = null;
$filename = "Upload " . date('Y-m-d H:i');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_FILES['reportFile']['tmp_name'])) {
        $content = file_get_contents($_FILES['reportFile']['tmp_name']);
        $filename = $_FILES['reportFile']['name'];
    } elseif (!empty($_POST['reportText'])) {
        $content = $_POST['reportText'];
        $filename = "Manual Paste " . date('Y-m-d H:i');
    }
}

// Fallback: Raw Input (For Chrome Extension / API)
if (!$content) {
    $content = file_get_contents("php://input");
    $filename = "Extension Upload " . date('Y-m-d H:i');
}

if (!$content) {
    die(json_encode(['status' => 'error', 'message' => 'No content provided']));
}

// 3. AUTHENTICATION CHECK
$userId = null;
if (isset($_SESSION['user_id'])) {
    // If logged in via browser
    $userId = $_SESSION['user_id'];
} else {
    // If coming from Extension/API, we try to detect if it's JSON.
    // If it is JSON, we allow it (Auto-upload). 
    // If it's NOT JSON (manual text upload attempt), we force login.
    $tempJson = json_decode($content, true);
    if (!$tempJson) {
        require_login();
        $user = current_user();
        $userId = $user['id'];
    }
}

// 4. DETECT & PROCESS FORMAT
$jsonData = json_decode($content, true);
$jsonReports = [];

// Determine if single object or array
if ($jsonData) {
    if (isset($jsonData['serviceProvider'])) {
        // Single Report
        $jsonReports[] = $jsonData;
    } elseif (is_array($jsonData) && isset($jsonData[0]['serviceProvider'])) {
        // Bulk List
        $jsonReports = $jsonData;
    }
}

if (!empty($jsonReports)) {
    // --- STRATEGY A: PROCESS JSON (Extension/Bulk) ---
    $createdIds = [];
    foreach ($jsonReports as $data) {
        $createdIds[] = saveAndParseJson($pdo, $data, $userId, $filename);
    }

    // If request came from the HTML Form (Browser)
    if (isset($_POST['reportText']) || isset($_FILES['reportFile'])) {
        if (count($createdIds) > 1) {
            header("Location: dashboard.php");
        } else {
            header("Location: view_report.php?id=" . $createdIds[0]);
        }
        exit;
    } else {
        // If request came from Extension (Return JSON)
        header('Content-Type: application/json');
        echo json_encode(["status" => "success", "report_ids" => $createdIds]);
        exit;
    }

} else {
    // --- STRATEGY B: PROCESS TEXT (Manual Regex) ---
    try {
        $stmt = $pdo->prepare("INSERT INTO raw_reports (filename, content, uploaded_by, service_provider, uploaded_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$filename, $content, $userId, 'Manual Upload']);
        $reportId = $pdo->lastInsertId();

        $parser = new ReportParser($content, $pdo, $reportId);
        $parser->parseAll();

        if (isset($_POST['reportText']) || isset($_FILES['reportFile'])) {
            header("Location: view_report.php?id=" . $reportId);
            exit;
        } else {
            echo json_encode(["status" => "success", "report_id" => $reportId]);
            exit;
        }
    } catch (PDOException $e) {
        die("Error: " . $e->getMessage());
    }
}

// --- HELPER: FILTERING (Test/Cancelled) ---
function shouldSkip($row) {
    foreach ($row as $val) {
        if (stripos($val, 'Test') !== false || stripos($val, 'Cancelled') !== false) {
            return true; 
        }
    }
    return false;
}

// --- HELPER: SAVE JSON ---
function saveAndParseJson($pdo, $data, $userId, $baseFilename) {
    $provider = $data['serviceProvider'] ?? 'Unknown';
    $contentStr = json_encode($data); 
    
    $stmt = $pdo->prepare("INSERT INTO raw_reports (filename, content, uploaded_by, service_provider, uploaded_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->execute([$baseFilename, $contentStr, $userId, $provider]);
    $reportId = $pdo->lastInsertId();

    $tables = $data['tables'] ?? [];

    // 1. PMS
    if (!empty($tables["dataTable"]["rows"])) {
        $stmt = $pdo->prepare("INSERT INTO pms_backlog (report_id, property_id, prop_name, count_value) VALUES (?, ?, ?, ?)");
        foreach ($tables["dataTable"]["rows"] as $row) {
            if (shouldSkip($row)) continue; 
            $stmt->execute([$reportId, $row["Property ID"] ?? 0, $row["Property Name"] ?? 'Unknown', $row["Count"] ?? 0]);
        }
    }
    // 2. Offline
    if (!empty($tables["dataTableOffline"]["rows"])) {
        $stmt = $pdo->prepare("INSERT INTO offline_rt1000 (report_id, property_id, prop_name, rt_name) VALUES (?, ?, ?, ?)");
        foreach ($tables["dataTableOffline"]["rows"] as $row) {
            if (shouldSkip($row)) continue;
            $stmt->execute([$reportId, $row["Property ID"] ?? 0, $row["Property Name"] ?? 'Unknown', $row["RT Name"] ?? 'Unknown']);
        }
    }
    // 3. Wakeup
    if (!empty($tables["wakeupDataTable"]["rows"])) {
        $stmt = $pdo->prepare("INSERT INTO wakeup_errors (report_id, property_id, prop_name, room_number, attempts, schedule_time, wakeup_time, status_text, room_status, pbx_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        foreach ($tables["wakeupDataTable"]["rows"] as $row) {
            if (shouldSkip($row)) continue;
            $sch = !empty($row["Schedule Time"]) ? date('Y-m-d H:i:s', strtotime($row["Schedule Time"])) : null;
            $wak = !empty($row["Wakeup Time"]) ? date('Y-m-d H:i:s', strtotime($row["Wakeup Time"])) : null;
            $stmt->execute([$reportId, $row["Property Id"] ?? 0, $row["Property Name"] ?? 'Unknown', $row["Room Number"] ?? '', $row["Attempts"] ?? 0, $sch, $wak, $row["Status"] ?? '', $row["Room Status"] ?? '', $row["PBX Type"] ?? '']);
        }
    }
    // 4. CDR
    if (!empty($tables["cdrDataTable"]["rows"])) {
        $stmt = $pdo->prepare("INSERT INTO cdr_status (report_id, property_id, prop_name, pbx_type, pbx_number, pbx_raw_seq, enterprise_code, group_code, last_posted_on) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        foreach ($tables["cdrDataTable"]["rows"] as $row) {
            if (shouldSkip($row)) continue;
            $posted = !empty($row["Last Posted On"]) ? date('Y-m-d H:i:s', strtotime($row["Last Posted On"])) : null;
            $stmt->execute([$reportId, $row["Property Id"] ?? 0, $row["Property Name"] ?? 'Unknown', $row["PBX Type"] ?? '', $row["PBX Number"] ?? '', $row["PBX Raw Seq"] ?? '', $row["Enterprise Code"] ?? '', $row["Group Code"] ?? '', $posted]);
        }
    }

    return $reportId;
}
?>