<?php
session_start();

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/app.php";

/* ===============================
   LOGIN CHECK
=================================*/
$isLoggedIn = isset($_SESSION['user_id']);
$isGuest = $isLoggedIn && ($_SESSION['role'] === 'guest');

/* ===============================
   GET ID
=================================*/
$id = intval($_GET['id'] ?? 0);

if ($id <= 0) {
    echo "Invalid equipment ID.";
    exit();
}

/* ===============================
   EQUIPMENT DETAILS
=================================*/
$stmt = mysqli_prepare($conn, "
    SELECT 
        e.*,
        d.name AS department_name
    FROM equipment e
    LEFT JOIN departments d 
        ON e.department_id = d.id
    WHERE e.id = ?
");

mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

$data = mysqli_fetch_assoc($result);

if (!$data) {
    echo "Equipment not found.";
    exit();
}

/* ===============================
   MAINTENANCE RECORDS
=================================*/
$maintenanceQuery = mysqli_prepare($conn, "
    SELECT 
        mr.*,
        u.full_name AS technician_name
    FROM maintenance_record mr
    LEFT JOIN users u 
        ON mr.technician_id = u.id
    WHERE mr.equipment_id = ?
    ORDER BY mr.maintenance_date DESC, mr.created_at DESC
");

mysqli_stmt_bind_param($maintenanceQuery, "i", $id);
mysqli_stmt_execute($maintenanceQuery);
$maintenanceResult = mysqli_stmt_get_result($maintenanceQuery);
?>

<!DOCTYPE html>
<html>
<head>

    <title>Equipment Details - QRCareTrack</title>

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

    <link rel="stylesheet" href="<?= BASE_URL ?>assets/style.css">
    <link rel="stylesheet" href="<?= BASE_URL ?>assets/details.css">

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

    <style>

        *{
            box-sizing:border-box;
        }

        body{
            margin:0;
            padding:0;
            overflow-x:hidden;
            background:#f5f7fb;
        }

        /* =========================
           MAIN
        ========================= */
        .main{
            padding:25px;
            margin-left: <?= (!$isGuest && $isLoggedIn) ? '220px' : '0' ?>;
        }

        /* =========================
           HEADER
        ========================= */
        .page-header{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:15px;
            margin-bottom:20px;
        }

        .page-header h1{
            margin:0;
        }

        .page-header p{
            margin-top:5px;
            color:#666;
        }

        /* =========================
           DETAILS
        ========================= */
        .details-container{
            display:grid;
            grid-template-columns:2fr 1fr;
            gap:20px;
        }

        .box{
            background:#fff;
            padding:25px;
            border-radius:14px;
            box-shadow:0 2px 10px rgba(0,0,0,0.08);
        }

        /* =========================
           INFO ROW
        ========================= */
        .info-row{
            display:flex;
            justify-content:space-between;
            align-items:flex-start;
            gap:20px;
            padding:14px 0;
            border-bottom:1px solid #eee;
        }

        .info-row span:first-child{
            font-weight:600;
            min-width:140px;
            color:#555;
        }

        .info-row strong,
        .info-row p{
            flex:1;
            text-align:right;
            margin:0;
            word-break:break-word;
        }

        /* =========================
           STATUS
        ========================= */
        .in-progress,
        .completed,
        .active,
        .under-maintenance,
        .inactive {
            padding: 6px 12px;
            border-radius: 8px;
            font-weight: 600;
            display: inline-block;
        }

        .completed,
        .active {
            background: #dcfce7;
            color: #166534;
        }

        .in-progress,
        .under-maintenance {
            background: #fef3c7;
            color: #92400e;
        }

        .inactive {
            background: #fee2e2;
            color: #b91c1c;
        }

        /* =========================
           BUTTONS
        ========================= */
        .service-wrapper,
        .report-wrapper {
            margin-top: 15px;
        }

        .service-btn,
        .report-btn,
        .login-btn,
        .btn {
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:10px;
            padding:12px 18px;
            border-radius:10px;
            color:#fff;
            text-decoration:none;
            font-weight:600;
        }

        .service-btn {
            background: #2563eb;
        }

        .service-btn:hover {
            background: #1d4ed8;
        }

        .report-btn {
            background: #dc2626;
        }

        .report-btn:hover {
            background: #b91c1c;
        }

        .login-btn {
            background: #16a34a;
        }

        .login-btn:hover {
            background: #15803d;
        }

        /* =========================
           QR
        ========================= */
        .qr-large{
            width:100%;
            max-width:220px;
            display:block;
            margin:auto;
        }

        /* =========================
           TABLE
        ========================= */
        .table-wrapper{
            width:100%;
            overflow-x:auto;
        }

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

        table th,
        table td {
            padding: 14px;
            border-bottom: 1px solid #eee;
            text-align: left;
            vertical-align: top;
        }

        table th {
            background: #fafafa;
            font-weight: 600;
        }

        .proof-img {
            width: 90px;
            height: 90px;
            object-fit: cover;
            border-radius: 10px;
            border: 1px solid #ddd;
        }

        /* =========================
           MOBILE
        ========================= */
        @media (max-width: 768px){

            .main{
                margin-left:0 !important;
                padding:15px;
                width:100%;
            }

            .page-header{
                flex-direction:column;
                align-items:flex-start;
            }

            .details-container{
                grid-template-columns:1fr;
            }

            .box{
                padding:18px;
            }

            .info-row{
                flex-direction:column;
                gap:8px;
            }

            .info-row strong,
            .info-row p{
                text-align:left;
                width:100%;
            }

            .service-btn,
            .report-btn,
            .login-btn,
            .btn{
                width:100%;
            }

            .qr-large{
                max-width:180px;
            }

            .proof-img{
                width:70px;
                height:70px;
            }

            table{
                display:block;
                overflow-x:auto;
                white-space:nowrap;
            }

            table th,
            table td{
                font-size:13px;
                padding:10px;
            }

        }

    </style>

</head>

<body>

<?php if ($isLoggedIn && !$isGuest): ?>
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>
<?php endif; ?>

<div class="main">

    <!-- HEADER -->
    <div class="page-header">

        <div>
            <h1>Equipment Details</h1>
            <p>View complete equipment information</p>
        </div>

        <?php if ($isLoggedIn): ?>

            <?php if ($isGuest): ?>

                <a href="<?= BASE_URL ?>auth/logout.php" class="btn" style="background:#dc2626;">
                    <i class="fas fa-right-from-bracket"></i>
                    Logout
                </a>

            <?php else: ?>

                <a href="<?= BASE_URL ?>items.php" class="btn" style="background:#6b7280;">
                    <i class="fas fa-arrow-left"></i>
                    Back
                </a>

            <?php endif; ?>

        <?php else: ?>

            <a href="<?= BASE_URL ?>auth/login.php?redirect=<?= urlencode($_SERVER['REQUEST_URI']) ?>" class="login-btn">
                <i class="fas fa-right-to-bracket"></i>
                Login
            </a>

        <?php endif; ?>

    </div>

    <div class="details-container">

       <!-- LEFT -->
        <div class="box">
        
            <h2><?= htmlspecialchars($data['equipment_name']) ?></h2>
        
            <div class="info-row">
                <span>Category</span>
                <strong><?= htmlspecialchars($data['category'] ?? '-') ?></strong>
            </div>
        
            <div class="info-row">
                <span>Department</span>
                <strong><?= htmlspecialchars($data['department_name'] ?? '-') ?></strong>
            </div>
        
            <div class="info-row">
                <span>Department ID</span>
                <strong><?= htmlspecialchars($data['department_id'] ?? '-') ?></strong>
            </div>
        
            <div class="info-row">
                <span>Status</span>
                <span class="<?= strtolower(str_replace(' ', '-', $data['status'])) ?>">
                    <?= htmlspecialchars($data['status']) ?>
                </span>
            </div>
        
            <div class="info-row">
                <span>Location ID</span>
                <strong><?= htmlspecialchars($data['location_id'] ?? '-') ?></strong>
            </div>
        
            <div class="info-row">
                <span>Location Name</span>
                <strong><?= htmlspecialchars($data['location'] ?? '-') ?></strong>
            </div>
        
            <div class="info-row">
                <span>Serial Number</span>
                <strong><?= htmlspecialchars($data['serial_number'] ?? '-') ?></strong>
            </div>
        
            <div class="info-row">
                <span>Purchase Date</span>
                <strong>
                    <?= !empty($data['purchase_date']) 
                        ? date("d M Y", strtotime($data['purchase_date'])) 
                        : '-' ?>
                </strong>
            </div>
        
            <div class="info-row">
                <span>Next Due Date</span>
                <strong>
                    <?= !empty($data['next_due_date']) 
                        ? date("d M Y, h:i A", strtotime($data['next_due_date'])) 
                        : '-' ?>
                </strong>
            </div>
        
            <div class="info-row">
                <span>Created At</span>
                <strong>
                    <?= !empty($data['created_at']) 
                        ? date("d M Y, h:i A", strtotime($data['created_at'])) 
                        : '-' ?>
                </strong>
            </div>
        
            <div class="info-row">
                <span>Description</span>
                <p><?= nl2br(htmlspecialchars($data['description'] ?? '-')) ?></p>
            </div>

            <!-- TECHNICIAN BUTTON -->
            <?php
            if (
                isset($_SESSION['role']) &&
                $_SESSION['role'] === 'technician' &&
                isset($_SESSION['department_id']) &&
                $_SESSION['department_id'] == $data['department_id']
            ):
            ?>

            <div class="service-wrapper">

                <a href="<?= BASE_URL ?>maintenance/service.php?id=<?= $data['id'] ?>" class="service-btn">
                    <i class="fas fa-screwdriver-wrench"></i>
                    Service Equipment
                </a>

            </div>

            <?php endif; ?>

            <!-- REPORT BUTTON -->
            <div class="report-wrapper">

                <?php if ($isLoggedIn): ?>

                    <a href="<?= BASE_URL ?>maintenance/create_report.php?id=<?= $data['id'] ?>" class="report-btn">
                        <i class="fas fa-triangle-exclamation"></i>
                        Create Report
                    </a>

                <?php else: ?>

                    <a href="<?= BASE_URL ?>auth/login.php?redirect=<?= urlencode($_SERVER['REQUEST_URI']) ?>" class="login-btn">
                        <i class="fas fa-right-to-bracket"></i>
                        Login to Continue
                    </a>

                <?php endif; ?>

            </div>

        </div>

        <!-- RIGHT -->
        <div class="box">

            <h3>QR Code</h3>

            <?php if (!empty($data['qr_code'])): ?>

    <img
        src="<?= BASE_URL ?>assets/qr_codes/<?= htmlspecialchars($data['qr_code']) ?>"
        class="qr-large"
    >

    <a
        href="<?= BASE_URL ?>assets/qr_codes/<?= htmlspecialchars($data['qr_code']) ?>"
        download="<?= htmlspecialchars($data['equipment_name']) ?>_QR.png"
        class="btn"
        style="background:#2563eb; margin-top:15px; width:100%;"
    >
        <i class="fas fa-download"></i>
        Download QR Code
    </a>
<?php if (
    isset($_SESSION['role']) &&
    $_SESSION['role'] === 'admin'
): ?>

<a
    href="<?= BASE_URL ?>equipment/regenerate_qr.php?id=<?= $data['id'] ?>"
    class="btn"
    style="background:#f59e0b; margin-top:10px; width:100%;"
    onclick="return confirm('Regenerate QR Code for this equipment?');"
>
    <i class="fas fa-qrcode"></i>
    Regenerate QR Code
</a>

<?php endif; ?>
<?php endif; ?>
            <hr style="margin:20px 0;">

            <div class="info-row">
                <span>Equipment ID</span>
                <strong><?= $data['id'] ?></strong>
            </div>

            <hr style="margin:20px 0;">

            <h3>Equipment Image</h3>

            <?php if (!empty($data['image']) && $data['image'] != 'placeholder.png'): ?>

                <img
                    src="<?= BASE_URL ?>assets/uploads/<?= htmlspecialchars($data['image']) ?>"
                    style="width:100%;border-radius:10px;"
                >

            <?php else: ?>

                <p>No Image Available</p>

            <?php endif; ?>

        </div>

    </div>

    <!-- MAINTENANCE -->
    <div class="box" style="margin-top:25px;">

        <h2>Maintenance Records</h2>

        <div class="table-wrapper">

            <table>

                <tr>
                    <th>Date</th>
                    <th>Technician</th>
                    <th>Description</th>
                    <th>Status</th>
                    <th>Proof</th>
                </tr>

                <?php while ($r = mysqli_fetch_assoc($maintenanceResult)): ?>

                    <tr>

                        <td>
                            <?= !empty($r['maintenance_date'])
                                ? date("d M Y", strtotime($r['maintenance_date']))
                                : '-' ?>
                        </td>

                        <td><?= htmlspecialchars($r['technician_name'] ?? '-') ?></td>

                        <td><?= htmlspecialchars($r['description'] ?? '-') ?></td>

                        <td>

                            <span class="<?= strtolower(str_replace(' ', '-', $r['status'])) ?>">
                                <?= htmlspecialchars($r['status']) ?>
                            </span>

                        </td>

                        <td>

                            <?php if (!empty($r['proof_image'])): ?>

                                <img
                                    src="<?= BASE_URL ?>assets/maintenance_proof/<?= htmlspecialchars($r['proof_image']) ?>"
                                    class="proof-img"
                                >

                            <?php else: ?>

                                -

                            <?php endif; ?>

                        </td>

                    </tr>

                <?php endwhile; ?>

            </table>

        </div>

    </div>

</div>

</body>
</html>