<?php
// public/delete_row.php
require __DIR__ . '/../src/auth.php';
require_login();
require __DIR__ . '/../src/db.php';

// Get inputs
$id = (int)($_GET['id'] ?? 0);
$table = $_GET['table'] ?? '';
$reportId = (int)($_GET['report_id'] ?? 0);
$tab = $_GET['tab'] ?? '';
$deleteAll = ($_GET['delete_all'] ?? '') === '1';

// Allowed tables
$allowedTables = [
    'raw_reports',
    'pms_backlog',
    'offline_rt1000',
    'cdr_status',
    'wakeup_errors',
];

// Validate table
if (!in_array($table, $allowedTables)) {
    header("Location: dashboard.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| DELETE ALL REPORTS (ONLY raw_reports)
|--------------------------------------------------------------------------
*/
if ($deleteAll && $table === 'raw_reports') {
    $pdo->exec("DELETE FROM raw_reports");
    header("Location: dashboard.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| DELETE SINGLE ROW (EXISTING BEHAVIOR)
|--------------------------------------------------------------------------
*/
if ($id) {
    $stmt = $pdo->prepare("DELETE FROM `$table` WHERE id = ?");
    $stmt->execute([$id]);

    if ($table === 'raw_reports') {
        header("Location: dashboard.php");
    } else {
        $redirectUrl = "view_report.php?id=" . $reportId;
        if ($tab) {
            $redirectUrl .= "#" . urlencode($tab);
        }
        header("Location: " . $redirectUrl);
    }
    exit;
}

// Fallback
header("Location: dashboard.php");
exit;
