<?php

require_once '../../vendor/autoload.php';
require_once '../../classes/Database.php';
require_once '../../classes/Logger.php';
require_once '../../includes/auth.php';

session_start();


$database = new Database();
$conn = $database->getConnection();


if (!$conn) {
    die("Database connection failed.");
}


$auth = new Auth($conn);


$auth->requireLogin();


if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit();
}


$visible_log_ids_json = $_POST['visible_log_ids'] ?? '[]';
$visible_log_ids = json_decode($visible_log_ids_json, true) ?? [];
$filter_user = $_POST['filter_user'] ?? '';
$filter_action = $_POST['filter_action'] ?? '';
$filter_module = $_POST['filter_module'] ?? '';
$filter_date_from = $_POST['filter_date_from'] ?? '';
$filter_date_to = $_POST['filter_date_to'] ?? '';
$limit = $_POST['limit'] ?? 100;


$query = "SELECT * FROM system_logs WHERE log_id IN (" . str_repeat('?,', count($visible_log_ids) - 1) . "?)";
$params = $visible_log_ids;


if (!empty($filter_user)) {
    $query .= " AND username LIKE ?";
    $params[] = '%' . $filter_user . '%';
}

if (!empty($filter_action)) {
    $query .= " AND action LIKE ?";
    $params[] = '%' . $filter_action . '%';
}

if (!empty($filter_module)) {
    $query .= " AND module = ?";
    $params[] = $filter_module;
}

if (!empty($filter_date_from)) {
    $query .= " AND DATE(timestamp) >= ?";
    $params[] = $filter_date_from;
}

if (!empty($filter_date_to)) {
    $query .= " AND DATE(timestamp) <= ?";
    $params[] = $filter_date_to;
}

$query .= " ORDER BY timestamp DESC LIMIT " . (int)$limit;


try {
    $stmt = $conn->prepare($query);
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Error retrieving logs: " . $e->getMessage());
}


require_once __DIR__ . '/../../vendor/tecnickcom/tcpdf/tcpdf.php';

class MYPDF extends TCPDF {
    public function Header() {
        $this->SetFont('helvetica', 'B', 16);
        $this->Cell(0, 15, 'System Activity Logs Report', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(10);
        $this->SetFont('helvetica', '', 10);
        $this->Cell(0, 10, 'Generated on: ' . date('F j, Y, g:i a'), 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(15);
    }

    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('helvetica', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('IMS System');
$pdf->SetTitle('System Logs Report');
$pdf->SetSubject('System Activity Logs');

$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

$pdf->AddPage();


$pdf->SetFont('helvetica', '', 9);


$header = array('Date', 'User', 'Action', 'Details', 'IP Address');
$w = array(25, 25, 35, 80, 25);


$pdf->SetFillColor(240, 240, 240);
$pdf->SetTextColor(0);
$pdf->SetDrawColor(0, 0, 0);
$pdf->SetLineWidth(0.3);
$pdf->SetFont('', 'B');

for($i = 0; $i < count($header); $i++) {
    $pdf->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
}
$pdf->Ln();


$pdf->SetFillColor(255, 255, 255);
$pdf->SetTextColor(0);
$pdf->SetFont('');

$fill = 0;
foreach($logs as $log) {
    $pdf->Cell($w[0], 6, date('m/d/Y', strtotime($log['timestamp'])), 'LR', 0, 'L', $fill);
    $pdf->Cell($w[1], 6, $log['username'], 'LR', 0, 'L', $fill);
    $pdf->Cell($w[2], 6, $log['action'], 'LR', 0, 'L', $fill);


    $details = str_replace(array("\r\n", "\n", "\r"), ' ', $log['details']);
    if(strlen($details) > 60) {
        $details = substr($details, 0, 57) . '...';
    }
    $pdf->Cell($w[3], 6, $details, 'LR', 0, 'L', $fill);

    $pdf->Cell($w[4], 6, $log['ip_address'], 'LR', 0, 'L', $fill);
    $pdf->Ln();
    $fill = !$fill;
}


$pdf->Cell(array_sum($w), 0, '', 'T');


$pdf->Ln(10);
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(0, 10, 'Summary', 0, 1, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 8, 'Total Logs Exported: ' . count($logs), 0, 1, 'L');
$pdf->Cell(0, 8, 'Export Date: ' . date('F j, Y, g:i a'), 0, 1, 'L');


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$logger->logAdmin('EXPORT_LOGS', 'Exported ' . count($logs) . ' system logs to PDF');


$filename = 'system_logs_' . date('Y-m-d_H-i-s') . '.pdf';
$pdf->Output($filename, 'D');
exit();
?>