<?php
session_start();

include($_SERVER['DOCUMENT_ROOT']."/SEAT/config/db.php");

require_once $_SERVER['DOCUMENT_ROOT'].
"/SEAT/vendor/dompdf/autoload.inc.php";

use Dompdf\Dompdf;
use Dompdf\Options;

/* =========================================================
   VALIDATION
========================================================= */

$event_id = intval($_GET['event_id'] ?? 0);

$type = $_GET['type'] ?? 'csv';

$tab = $_GET['tab'] ?? 'attendance';

/* =========================================================
   EVENT
========================================================= */

$event = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT
e.*,
o.club_name
FROM events e

LEFT JOIN organizers o
ON e.organizer_id = o.id

WHERE e.id='$event_id'
"));

if(!$event){

    die("Event not found");
}

/* =========================================================
   TOTAL REGISTRATION
========================================================= */

$total = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT COUNT(*) total
FROM event_registrations
WHERE event_id='$event_id'
"))['total'];

/* =========================================================
   ATTENDANCE
========================================================= */

$attendance = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT COUNT(*) total
FROM attendances
WHERE event_id='$event_id'
"))['total'];

$rate = $total > 0
? round(($attendance / $total) * 100,1)
: 0;

/* =========================================================
   REVENUE
========================================================= */

$revenue =
$total * $event['fee_amount'];

$date =
date("d M Y h:i:s A");

/* =========================================================
   REPORT CONFIG
========================================================= */

$reportTitle = "";
$tableHeaders = [];
$list = false;

/* =========================================================
   PARTICIPANT LIST
========================================================= */

if($tab=="participants"){

    $reportTitle =
    "PARTICIPANT LIST REPORT";

    $tableHeaders = [
        "No",
        "Name",
        "ID",
        "Email",
        "Registered Date"
    ];

    $list = mysqli_query($conn,"
    SELECT
        p.full_name,
        p.matric_no,
        p.staff_no,
        u.email,
        r.registered_at

    FROM event_registrations r

    INNER JOIN participants p
    ON p.id = r.participant_id

    INNER JOIN users u
    ON u.id = p.user_id

    WHERE r.event_id='$event_id'

    ORDER BY r.registered_at DESC
    ");
}

/* =========================================================
   ATTENDANCE LIST
========================================================= */

elseif($tab=="attendance"){

    $reportTitle =
    "ATTENDANCE LIST REPORT";

    $tableHeaders = [
        "No",
        "Name",
        "ID",
        "Date",
        "Time"
    ];

    $list = mysqli_query($conn,"
    SELECT
        p.full_name,
        p.matric_no,
        p.staff_no,
        a.checked_in_at

    FROM attendances a

    INNER JOIN event_registrations r
    ON r.id = a.registration_id

    INNER JOIN participants p
    ON p.id = r.participant_id

    WHERE a.event_id='$event_id'

    ORDER BY a.checked_in_at ASC
    ");
}

/* =========================================================
   REFUND LIST
========================================================= */

elseif($tab=="refund"){

    $reportTitle =
    "REFUND LIST REPORT";

    $tableHeaders = [
        "No",
        "Name",
        "ID",
        "Phone",
        "Refund Amount"
    ];

    $list = mysqli_query($conn,"
    SELECT
        p.full_name,
        p.matric_no,
        p.staff_no,
        p.phone

    FROM event_registrations r

    INNER JOIN participants p
    ON p.id = r.participant_id

    WHERE r.event_id='$event_id'
    AND r.payment_status='Paid'

    ORDER BY p.full_name ASC
    ");
}

/* =========================================================
   INVALID TAB
========================================================= */

if(!$list){

    die("Invalid report type");
}

/* =========================================================
   CSV EXPORT
========================================================= */

if($type=="csv"){

    header("Content-Type: text/csv");

    header("
    Content-Disposition: attachment;
    filename=".$tab."_report.csv
    ");

    echo $reportTitle."\n";
    echo "============================\n\n";

    echo "Event: ".$event['title']."\n";

    echo "Date: ".
    date(
        "d M Y",
        strtotime($event['event_date'])
    )."\n";

    echo "Status: ".
    strtoupper($event['status'])."\n";

    echo "Organizer: ".
    $event['club_name']."\n\n";

    echo "STATISTICS\n";
    echo "------------------\n";

    echo "Total Registrations: $total\n";

    echo "Attendance: $attendance\n";

    echo "Attendance Rate: $rate%\n";

    if($event['fee_type']=="Free"){

        echo "Revenue: FREE\n\n";

    }else{

        echo "Revenue: RM ".
        number_format($revenue,2).
        "\n\n";
    }

    echo implode(",", $tableHeaders)."\n";

    $i = 1;

    while($r=mysqli_fetch_assoc($list)){

        /* PARTICIPANT */

        if($tab=="participants"){

            echo
            $i.",".
            $r['full_name'].",".
            ($r['matric_no']
            ?: $r['staff_no']).",".
            $r['email'].",".
            date(
                "d M Y",
                strtotime(
                    $r['registered_at']
                )
            )."\n";
        }

        /* ATTENDANCE */

        elseif($tab=="attendance"){

            echo
            $i.",".
            $r['full_name'].",".
            ($r['matric_no']
            ?: $r['staff_no']).",".
            date(
                "d M Y",
                strtotime(
                    $r['checked_in_at']
                )
            ).",".
            date(
                "g:i A",
                strtotime(
                    $r['checked_in_at']
                )
            )."\n";
        }

        /* REFUND */

        elseif($tab=="refund"){

            echo
            $i.",".
            $r['full_name'].",".
            ($r['matric_no']
            ?: $r['staff_no']).",".
            $r['phone'].",".
            "RM ".
            number_format(
                $event['fee_amount'],
                2
            )."\n";
        }

        $i++;
    }

    echo "\nGenerated on: ".$date;

    exit;
}

/* =========================================================
   PDF EXPORT
========================================================= */

if($type=="pdf"){

ob_start();

?>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<style>

body{
    font-family: DejaVu Sans, sans-serif;
    font-size:13px;
    color:#222;
}

.title{
    text-align:center;
    font-size:20px;
    font-weight:bold;
    margin-bottom:4px;
}

.prepared{
    text-align:center;
    font-size:12px;
    color:#666;
    margin-bottom:20px;
}

.info{
    margin-bottom:18px;
}

.info div{
    margin:5px 0;
}

.section{
    margin:18px 0 10px 0;
    font-weight:bold;
}

.table{
    width:100%;
    border-collapse:collapse;
}

.table th{
    background:#4f46e5;
    color:white;
    padding:9px;
    border:1px solid #d1d5db;
    text-align:left;
    font-size:12px;
}

.table td{
    padding:8px;
    border:1px solid #e5e7eb;
    font-size:12px;
}

.table tr:nth-child(even){
    background:#fafafa;
}

.footer{
    margin-top:16px;
    font-size:11px;
    color:#666;
}

</style>

</head>

<body>

<div class="title">

    <?= $reportTitle ?>

</div>

<div class="prepared">

    Prepared by:
    <?= $event['club_name'] ?>

</div>

<div class="info">

    <div>
        <b>Event:</b>
        <?= $event['title'] ?>
    </div>

    <div>
        <b>Event Date:</b>

        <?= date(
            "d M Y",
            strtotime(
                $event['event_date']
            )
        ) ?>
    </div>

    <div>
        <b>Status:</b>

        <?= strtoupper(
            $event['status']
        ) ?>
    </div>

    <div>
        <b>Total Registrations:</b>

        <?= $total ?>
    </div>

    <div>
        <b>Attendance:</b>

        <?= $attendance ?>
        /
        <?= $total ?>

        (<?= $rate ?>%)
    </div>

</div>

<div class="section">

    <?= strtoupper($tab) ?> TABLE

</div>

<table class="table">

<tr>

<?php foreach($tableHeaders as $head): ?>

<th>
    <?= $head ?>
</th>

<?php endforeach; ?>

</tr>

<?php

$i = 1;

mysqli_data_seek($list,0);

while($r=mysqli_fetch_assoc($list)):

?>

<tr>

<td>
    <?= $i++ ?>
</td>

<?php if($tab=="participants"): ?>

<td>
    <?= $r['full_name'] ?>
</td>

<td>
    <?= $r['matric_no']
    ?: $r['staff_no'] ?>
</td>

<td>
    <?= $r['email'] ?>
</td>

<td>
    <?= date(
        "d M Y",
        strtotime(
            $r['registered_at']
        )
    ) ?>
</td>

<?php elseif($tab=="attendance"): ?>

<td>
    <?= $r['full_name'] ?>
</td>

<td>
    <?= $r['matric_no']
    ?: $r['staff_no'] ?>
</td>

<td>
    <?= date(
        "d M Y",
        strtotime(
            $r['checked_in_at']
        )
    ) ?>
</td>

<td>
    <?= date(
        "g:i A",
        strtotime(
            $r['checked_in_at']
        )
    ) ?>
</td>

<?php elseif($tab=="refund"): ?>

<td>
    <?= $r['full_name'] ?>
</td>

<td>
    <?= $r['matric_no']
    ?: $r['staff_no'] ?>
</td>

<td>
    <?= $r['phone'] ?>
</td>

<td>
    RM <?= number_format(
        $event['fee_amount'],
        2
    ) ?>
</td>

<?php endif; ?>

</tr>

<?php endwhile; ?>

</table>

<div class="footer">

    Generated on:
    <?= $date ?>

</div>

</body>

</html>

<?php

$html = ob_get_clean();

/* =========================================================
   DOMPDF
========================================================= */

$options = new Options();

$options->set(
    'isRemoteEnabled',
    true
);

$dompdf =
new Dompdf($options);

$dompdf->loadHtml($html);

$dompdf->setPaper(
    'A4',
    'portrait'
);

$dompdf->render();

$dompdf->stream(
    $tab."_report.pdf",
    ["Attachment"=>false]
);

exit;

}
?>