<?php

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

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

if (!$id) {
    exit('Invalid inventory ID.');
}


$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);

if (!$surveyStatement) {
    exit('Unable to load inventory details.');
}

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

mysqli_stmt_bind_param(
    $surveyStatement,
    $parameterTypes,
    ...$parameterValues
);

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('Inventory record not found or access denied.');
}

/*
|--------------------------------------------------------------------------
| Role-based permission
|--------------------------------------------------------------------------
*/

if (!canAccessSurvey($survey)) {
    http_response_code(403);
    exit('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'
);

if (!$standardStatement) {
    exit('Unable to load fixed-unit equipment.');
}

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

mysqli_stmt_execute($standardStatement);

$standardResult = mysqli_stmt_get_result(
    $standardStatement
);

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

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

    $standardSections[$sectionName][] = $row;
}

mysqli_stmt_close($standardStatement);

/*
|--------------------------------------------------------------------------
| Load Other Units and custom 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.unit_name ASC,
        soe.display_order ASC,
        soe.equipment_name ASC'
);

if (!$otherStatement) {
    exit('Unable to load other-unit equipment.');
}

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);

include '../includes/header.php';
include '../includes/navbar.php';

$grandWorking = 0;
$grandNotWorking = 0;
$grandRepair = 0;
?>

<main class="container mt-4 mb-5">

    <div class="d-flex flex-column flex-md-row
                justify-content-between align-items-md-center gap-2 mb-3">

        <div>
            <h4 class="mb-1">
                <i class="fa-solid fa-clipboard-list me-1"></i>
                Inventory Details
            </h4>

            <span class="text-muted">
                Inventory ID: <?= (int)$survey['id'] ?>
            </span>
        </div>

        <div class="d-flex gap-2">

            <a
                href="view_surveys.php"
                class="btn btn-secondary">

                <i class="fa-solid fa-arrow-left"></i>
                Back

            </a>

            <a
                href="print_survey.php?id=<?= (int)$survey['id'] ?>"
                class="btn btn-primary"
                target="_blank">

                <i class="fa-solid fa-print"></i>
                Print

            </a>

        </div>

    </div>

    <!-- School information -->
    <div class="card shadow mb-4">

        <div class="card-header bg-primary text-white">
            <strong>
                <i class="fa-solid fa-school me-1"></i>
                School Information
            </strong>
        </div>

        <div class="card-body">

            <div class="row g-3">

                <div class="col-md-6">
                    <strong>School:</strong><br>
                    <?= htmlspecialchars($survey['school_name']) ?>
                </div>

                <div class="col-md-3">
                    <strong>Census No:</strong><br>
                    <?= htmlspecialchars($survey['census_no']) ?>
                </div>

                <div class="col-md-3">
                    <strong>Inventory Date:</strong><br>
                    <?= htmlspecialchars($survey['survey_date']) ?>
                </div>

                <div class="col-md-4">
                    <strong>District:</strong><br>
                    <?= htmlspecialchars($survey['district']) ?>
                </div>

                <div class="col-md-4">
                    <strong>Zone:</strong><br>
                    <?= htmlspecialchars($survey['zone_name']) ?>
                </div>

                <div class="col-md-4">
                    <strong>Division:</strong><br>
                    <?= htmlspecialchars($survey['division_name']) ?>
                </div>

                <div class="col-md-4">
                    <strong>National / Provincial:</strong><br>
                    <?= htmlspecialchars($survey['school_category']) ?>
                </div>

                <div class="col-md-4">
                    <strong>School Type:</strong><br>
                    <?= htmlspecialchars($survey['school_type']) ?>
                </div>

                <div class="col-md-4">
                    <strong>Entered By:</strong><br>
                    <?= htmlspecialchars($survey['entered_by']) ?>
                </div>

            </div>

        </div>

    </div>

    <!-- Contact information -->
    <div class="card shadow mb-4">

        <div class="card-header bg-info text-white">
            <strong>
                <i class="fa-solid fa-address-book me-1"></i>
                Contact Information
            </strong>
        </div>

        <div class="card-body">

            <div class="row g-3">

                <div class="col-md-4">
                    <strong>Principal Name:</strong><br>
                    <?= htmlspecialchars($survey['principal_name'] ?: '-') ?>
                </div>

                <div class="col-md-4">
                    <strong>Principal Phone:</strong><br>
                    <?= htmlspecialchars($survey['principal_phone'] ?: '-') ?>
                </div>

                <div class="col-md-4">
                    <strong>School Phone:</strong><br>
                    <?= htmlspecialchars($survey['school_phone'] ?: '-') ?>
                </div>

                <div class="col-md-6">
                    <strong>IT Teacher Name:</strong><br>
                    <?= htmlspecialchars($survey['it_teacher_name'] ?: '-') ?>
                </div>

                <div class="col-md-6">
                    <strong>IT Teacher Phone:</strong><br>
                    <?= htmlspecialchars($survey['it_teacher_phone'] ?: '-') ?>
                </div>

            </div>

        </div>

    </div>

    <!-- Fixed units -->
    <?php foreach ($standardSections as $section => $items) { ?>

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

        <div class="card shadow mb-4">

            <div class="card-header bg-primary text-white">
                <strong>
                    <?= htmlspecialchars($section) ?>
                </strong>
            </div>

            <div class="table-responsive">

                <table class="table table-bordered align-middle mb-0">

                    <thead class="table-dark">

                        <tr>
                            <th>Equipment</th>
                            <th width="130">Working</th>
                            <th width="140">Not Working</th>
                            <th width="120">Repair</th>
                            <th width="120">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']) ?>
                            </td>

                            <td><?= $working ?></td>
                            <td><?= $notWorking ?></td>
                            <td><?= $repair ?></td>
                            <td class="fw-bold"><?= $total ?></td>
                        </tr>

                    <?php } ?>

                    <?php
                    $unitTotal =
                        $unitWorking +
                        $unitNotWorking +
                        $unitRepair;
                    ?>

                    <tr class="table-primary fw-bold">
                        <td>Unit Total</td>
                        <td><?= $unitWorking ?></td>
                        <td><?= $unitNotWorking ?></td>
                        <td><?= $unitRepair ?></td>
                        <td><?= $unitTotal ?></td>
                    </tr>

                    </tbody>

                </table>

            </div>

        </div>

    <?php } ?>

    <!-- Other Units -->
    <?php foreach ($otherUnits as $otherUnit) { ?>

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

        <div class="card shadow mb-4">

            <div class="card-header bg-secondary text-white">
                <strong>
                    <i class="fa-solid fa-building me-1"></i>
                    <?= htmlspecialchars($otherUnit['unit_name']) ?>
                </strong>
            </div>

            <?php if ($otherUnit['details'] !== '') { ?>

                <div class="card-body border-bottom">
                    <?= nl2br(htmlspecialchars($otherUnit['details'])) ?>
                </div>

            <?php } ?>

            <div class="table-responsive">

                <table class="table table-bordered align-middle mb-0">

                    <thead class="table-dark">

                        <tr>
                            <th>Equipment</th>
                            <th width="130">Working</th>
                            <th width="140">Not Working</th>
                            <th width="120">Repair</th>
                            <th width="120">Total</th>
                        </tr>

                    </thead>

                    <tbody>

                    <?php foreach ($otherUnit['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']) ?>
                            </td>

                            <td><?= $working ?></td>
                            <td><?= $notWorking ?></td>
                            <td><?= $repair ?></td>
                            <td class="fw-bold"><?= $total ?></td>
                        </tr>

                    <?php } ?>

                    <?php
                    $unitTotal =
                        $unitWorking +
                        $unitNotWorking +
                        $unitRepair;
                    ?>

                    <tr class="table-secondary fw-bold">
                        <td>Unit Total</td>
                        <td><?= $unitWorking ?></td>
                        <td><?= $unitNotWorking ?></td>
                        <td><?= $unitRepair ?></td>
                        <td><?= $unitTotal ?></td>
                    </tr>

                    </tbody>

                </table>

            </div>

        </div>

    <?php } ?>

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

    <!-- Overall totals -->
    <div class="card shadow mb-4">

        <div class="card-header bg-success text-white">
            <strong>
                <i class="fa-solid fa-chart-simple me-1"></i>
                Overall Inventory Totals
            </strong>
        </div>

        <div class="card-body">

            <div class="row text-center">

                <div class="col-6 col-md-3 mb-3">
                    <small class="text-muted d-block">
                        Working
                    </small>

                    <h3 class="text-success mb-0">
                        <?= $grandWorking ?>
                    </h3>
                </div>

                <div class="col-6 col-md-3 mb-3">
                    <small class="text-muted d-block">
                        Not Working
                    </small>

                    <h3 class="text-danger mb-0">
                        <?= $grandNotWorking ?>
                    </h3>
                </div>

                <div class="col-6 col-md-3 mb-3">
                    <small class="text-muted d-block">
                        Repair
                    </small>

                    <h3 class="text-warning mb-0">
                        <?= $grandRepair ?>
                    </h3>
                </div>

                <div class="col-6 col-md-3 mb-3">
                    <small class="text-muted d-block">
                        Grand Total
                    </small>

                    <h3 class="text-primary mb-0">
                        <?= $grandTotal ?>
                    </h3>
                </div>

            </div>

        </div>

    </div>

    <?php if (!$standardSections && !$otherUnits) { ?>

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

    <?php } ?>

</main>

<?php include '../includes/footer.php'; ?>