<?php

declare(strict_types=1);

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/role_filter.php';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT,
    [
        'options' => [
            'min_range' => 1
        ]
    ]
);

if (!$id) {
    http_response_code(400);
    exit('Invalid survey ID.');
}

/*
|--------------------------------------------------------------------------
| Load survey with role filtering
|--------------------------------------------------------------------------
*/

$roleFilter = getSurveyRoleFilter('s');

$surveySql = '
    SELECT
        s.id,
        s.survey_date,
        s.entered_by,
        s.census_no,
        s.district,
        s.zone_name,
        s.division_name,
        s.school_name,
        s.school_category,
        s.school_type,
        s.principal_name,
        s.principal_phone,
        s.school_phone,
        s.it_teacher_name,
        s.it_teacher_phone
    FROM surveys s
    WHERE s.id = ?
    ' . $roleFilter['sql'] . '
    LIMIT 1
';

$surveyStatement = mysqli_prepare($conn, $surveySql);

$surveyTypes = 'i' . $roleFilter['types'];
$surveyParameters = array_merge(
    [$id],
    $roleFilter['params']
);

mysqli_stmt_bind_param(
    $surveyStatement,
    $surveyTypes,
    ...$surveyParameters
);

mysqli_stmt_execute($surveyStatement);

$surveyResult = mysqli_stmt_get_result($surveyStatement);
$survey = mysqli_fetch_assoc($surveyResult);

mysqli_stmt_close($surveyStatement);

if (!$survey) {
    http_response_code(404);
    exit('Survey not found or access denied.');
}

/*
|--------------------------------------------------------------------------
| Load fixed-unit equipment
|--------------------------------------------------------------------------
*/

$standardSections = [];

$standardStatement = mysqli_prepare(
    $conn,
    'SELECT
        sed.section,
        em.equipment_name,
        sed.working,
        sed.not_working,
        sed.repair
     FROM survey_equipment_details sed
     INNER JOIN equipment_master em
        ON em.id = sed.equipment_id
     WHERE sed.survey_id = ?
     ORDER BY
        sed.section ASC,
        em.display_order ASC,
        em.equipment_name ASC'
);

mysqli_stmt_bind_param(
    $standardStatement,
    'i',
    $id
);

mysqli_stmt_execute($standardStatement);

$standardResult = mysqli_stmt_get_result($standardStatement);

while ($row = mysqli_fetch_assoc($standardResult)) {
    $sectionName = (string)$row['section'];

    if (!isset($standardSections[$sectionName])) {
        $standardSections[$sectionName] = [];
    }

    $standardSections[$sectionName][] = [
        'equipment_name' => $row['equipment_name'],
        'working' => (int)$row['working'],
        'not_working' => (int)$row['not_working'],
        'repair' => (int)$row['repair']
    ];
}

mysqli_stmt_close($standardStatement);

/*
|--------------------------------------------------------------------------
| Load other units and equipment
|--------------------------------------------------------------------------
*/

$otherUnits = [];

$otherStatement = mysqli_prepare(
    $conn,
    'SELECT
        sou.id AS other_unit_id,
        sou.unit_name,
        sou.details,
        sou.display_order AS unit_order,
        soe.equipment_name,
        soe.working,
        soe.not_working,
        soe.repair,
        soe.display_order AS equipment_order
     FROM survey_other_units sou
     LEFT JOIN survey_other_equipment soe
        ON soe.other_unit_id = sou.id
     WHERE sou.survey_id = ?
     ORDER BY
        sou.display_order ASC,
        sou.id ASC,
        soe.display_order ASC,
        soe.id ASC'
);

mysqli_stmt_bind_param(
    $otherStatement,
    'i',
    $id
);

mysqli_stmt_execute($otherStatement);

$otherResult = mysqli_stmt_get_result($otherStatement);

while ($row = mysqli_fetch_assoc($otherResult)) {
    $otherUnitId = (int)$row['other_unit_id'];

    if (!isset($otherUnits[$otherUnitId])) {
        $otherUnits[$otherUnitId] = [
            'unit_name' => $row['unit_name'],
            'details' => $row['details'] ?? '',
            'equipment' => []
        ];
    }

    if ($row['equipment_name'] !== null) {
        $otherUnits[$otherUnitId]['equipment'][] = [
            'equipment_name' => $row['equipment_name'],
            'working' => (int)$row['working'],
            'not_working' => (int)$row['not_working'],
            'repair' => (int)$row['repair']
        ];
    }
}

mysqli_stmt_close($otherStatement);

$grandWorking = 0;
$grandNotWorking = 0;
$grandRepair = 0;

function printValue(mixed $value): string
{
    $text = trim((string)$value);

    return htmlspecialchars(
        $text !== '' ? $text : '-',
        ENT_QUOTES,
        'UTF-8'
    );
}

function printDateValue(?string $value): string
{
    if (!$value) {
        return '-';
    }

    $timestamp = strtotime($value);

    if ($timestamp === false) {
        return printValue($value);
    }

    return htmlspecialchars(
        date('Y-m-d H:i', $timestamp),
        ENT_QUOTES,
        'UTF-8'
    );
}


?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Survey #<?= (int)$survey['id'] ?> Print
    </title>

    <link
        href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
        rel="stylesheet"
    >

    <link
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
        rel="stylesheet"
    >

    <link
        href="<?= htmlspecialchars(
            BASE_URL
            . 'assets/css/style.css?v='
            . urlencode(SYSTEM_VERSION),
            ENT_QUOTES,
            'UTF-8'
        ) ?>"
        rel="stylesheet"
    >

</head>

<body class="print-survey-page">

    <div class="print-toolbar no-print d-flex justify-content-between">

        <a
            href="<?= htmlspecialchars(
            BASE_URL . 'surveys/view_survey.php?id=' . (int)$survey['id'],
            ENT_QUOTES,
            'UTF-8'
        ) ?>"
            class="btn btn-secondary"
        >
            <i class="fa-solid fa-arrow-left me-1"></i>
            Back
        </a>

        <button
            type="button"
            class="btn btn-primary"
            onclick="window.print()"
        >
            <i class="fa-solid fa-print me-1"></i>
            Print
        </button>

    </div>

    <main class="print-page">

        <div class="report-title">

            <h2>
                Sabaragamuwa Province School Computer Hardware Inventory System
            </h2>

            <p>
                <strong>Survey Details Report</strong>
            </p>

            <p class="small">
                Survey ID: <?= (int)$survey['id'] ?>
            </p>

        </div>

        <div class="section-title">
            School Information
        </div>

        <table class="info-table">

            <tbody>

                <tr>
                    <th>School Name</th>
                    <td colspan="3">
                        <?= printValue($survey['school_name']) ?>
                    </td>
                </tr>

                <tr>
                    <th>Census No.</th>
                    <td><?= printValue($survey['census_no']) ?></td>

                    <th>Survey Date</th>
                    <td><?= printDateValue($survey['survey_date']) ?></td>
                </tr>

                <tr>
                    <th>District</th>
                    <td><?= printValue($survey['district']) ?></td>

                    <th>Zone</th>
                    <td><?= printValue($survey['zone_name']) ?></td>
                </tr>

                <tr>
                    <th>Division</th>
                    <td><?= printValue($survey['division_name']) ?></td>

                    <th>Entered By</th>
                    <td><?= printValue($survey['entered_by']) ?></td>
                </tr>

                <tr>
                    <th>Category</th>
                    <td><?= printValue($survey['school_category']) ?></td>

                    <th>School Type</th>
                    <td><?= printValue($survey['school_type']) ?></td>
                </tr>

            </tbody>

        </table>

        <div class="section-title">
            Contact Information
        </div>

        <table class="info-table">

            <tbody>

                <tr>
                    <th>Principal Name</th>
                    <td><?= printValue($survey['principal_name']) ?></td>

                    <th>Principal Phone</th>
                    <td><?= printValue($survey['principal_phone']) ?></td>
                </tr>

                <tr>
                    <th>School Phone</th>
                    <td><?= printValue($survey['school_phone']) ?></td>

                    <th>IT Teacher Name</th>
                    <td><?= printValue($survey['it_teacher_name']) ?></td>
                </tr>

                <tr>
                    <th>IT Teacher Phone</th>
                    <td colspan="3">
                        <?= printValue($survey['it_teacher_phone']) ?>
                    </td>
                </tr>

            </tbody>

        </table>

        <?php foreach ($standardSections as $section => $items): ?>

            <?php
            $unitWorking = 0;
            $unitNotWorking = 0;
            $unitRepair = 0;
            ?>

            <div class="section-title">
                <?= htmlspecialchars(
                    $section,
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>
            </div>

            <table class="equipment-table">

                <thead>

                    <tr>
                        <th>Equipment</th>
                        <th>Working</th>
                        <th>Not Working</th>
                        <th>Repair</th>
                        <th>Total</th>
                    </tr>

                </thead>

                <tbody>

                    <?php foreach ($items as $item): ?>

                        <?php
                        $working = (int)$item['working'];
                        $notWorking = (int)$item['not_working'];
                        $repair = (int)$item['repair'];
                        $total = $working + $notWorking + $repair;

                        $unitWorking += $working;
                        $unitNotWorking += $notWorking;
                        $unitRepair += $repair;

                        $grandWorking += $working;
                        $grandNotWorking += $notWorking;
                        $grandRepair += $repair;
                        ?>

                        <tr>
                            <td>
                                <?= htmlspecialchars(
                                    $item['equipment_name'],
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </td>

                            <td><?= $working ?></td>
                            <td><?= $notWorking ?></td>
                            <td><?= $repair ?></td>
                            <td><?= $total ?></td>
                        </tr>

                    <?php endforeach; ?>

                    <tr class="unit-total">
                        <td>Unit Total</td>
                        <td><?= $unitWorking ?></td>
                        <td><?= $unitNotWorking ?></td>
                        <td><?= $unitRepair ?></td>
                        <td>
                            <?= $unitWorking + $unitNotWorking + $unitRepair ?>
                        </td>
                    </tr>

                </tbody>

            </table>

        <?php endforeach; ?>

        <?php foreach ($otherUnits as $unit): ?>

            <?php
            $unitWorking = 0;
            $unitNotWorking = 0;
            $unitRepair = 0;
            ?>

            <div class="section-title">
                <?= htmlspecialchars(
                    $unit['unit_name'],
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>
            </div>

            <?php if (trim((string)$unit['details']) !== ''): ?>

                <div class="border border-dark border-top-0 p-2 small">
                    <strong>Details:</strong>

                    <?= nl2br(
                        htmlspecialchars(
                            $unit['details'],
                            ENT_QUOTES,
                            'UTF-8'
                        )
                    ) ?>
                </div>

            <?php endif; ?>

            <table class="equipment-table">

                <thead>

                    <tr>
                        <th>Equipment</th>
                        <th>Working</th>
                        <th>Not Working</th>
                        <th>Repair</th>
                        <th>Total</th>
                    </tr>

                </thead>

                <tbody>

                    <?php if ($unit['equipment'] === []): ?>

                        <tr>
                            <td colspan="5">
                                No equipment records.
                            </td>
                        </tr>

                    <?php else: ?>

                        <?php foreach ($unit['equipment'] as $item): ?>

                            <?php
                            $working = (int)$item['working'];
                            $notWorking = (int)$item['not_working'];
                            $repair = (int)$item['repair'];
                            $total = $working + $notWorking + $repair;

                            $unitWorking += $working;
                            $unitNotWorking += $notWorking;
                            $unitRepair += $repair;

                            $grandWorking += $working;
                            $grandNotWorking += $notWorking;
                            $grandRepair += $repair;
                            ?>

                            <tr>
                                <td>
                                    <?= htmlspecialchars(
                                        $item['equipment_name'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </td>

                                <td><?= $working ?></td>
                                <td><?= $notWorking ?></td>
                                <td><?= $repair ?></td>
                                <td><?= $total ?></td>
                            </tr>

                        <?php endforeach; ?>

                    <?php endif; ?>

                    <tr class="unit-total">
                        <td>Unit Total</td>
                        <td><?= $unitWorking ?></td>
                        <td><?= $unitNotWorking ?></td>
                        <td><?= $unitRepair ?></td>
                        <td>
                            <?= $unitWorking + $unitNotWorking + $unitRepair ?>
                        </td>
                    </tr>

                </tbody>

            </table>

        <?php endforeach; ?>

        <?php
        $grandTotal =
            $grandWorking +
            $grandNotWorking +
            $grandRepair;
        ?>

        <div class="section-title">
            Overall Inventory Totals
        </div>

        <div class="row g-0">

            <div class="col-3">
                <div class="grand-total-box">
                    Working
                    <strong><?= $grandWorking ?></strong>
                </div>
            </div>

            <div class="col-3">
                <div class="grand-total-box">
                    Not Working
                    <strong><?= $grandNotWorking ?></strong>
                </div>
            </div>

            <div class="col-3">
                <div class="grand-total-box">
                    Repair
                    <strong><?= $grandRepair ?></strong>
                </div>
            </div>

            <div class="col-3">
                <div class="grand-total-box">
                    Grand Total
                    <strong><?= $grandTotal ?></strong>
                </div>
            </div>

        </div>

        <?php if ($standardSections === [] && $otherUnits === []): ?>

            <div class="alert alert-warning mt-3">
                No equipment records exist for this survey.
            </div>

        <?php endif; ?>

    </main>

</body>

</html>