<?php

require_once dirname(__DIR__) . '/models/Asset.php';
require_once dirname(__DIR__) . '/models/Ticket.php';
require_once dirname(__DIR__) . '/models/SlaIncident.php';
require_once dirname(__DIR__) . '/../config/db.php';

class DashboardController {
    private $conn;

    public function __construct() {
        $this->conn = connectDB();
    }

    public function index() {
        // Current month and year for monthly KPIs
        $currentMonth = date('m');
        $currentYear = date('Y');

        // Fetch data for the new cards
        $totalAssets = $this->getAssetCount();
        $totalMaintenanceThisMonth = $this->getTotalMaintenanceCountByMonth($currentMonth, $currentYear);
        $assetsDamaged = $this->getAssetCountByStatus('Rusak');
        $assetsNeedRepair = $this->getAssetCountByStatus('Maintenance'); // Interpreting 'Perlu Perbaikan' as 'Maintenance' status

        echo "<div class='row row-cols-1 row-cols-md-2 row-cols-lg-2 g-3 mb-4'>"; /* Use g-3 for tighter spacing, mb-4 for bottom margin */

        // Widget 1: Total Aset
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-blue h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-box-seam fs-1 text-primary me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Total Aset</div>
                                <div class='fw-bold fs-2 text-primary'>{$totalAssets}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        // Widget 2: Total Aset Maintenance (Perbulan ini)
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-info h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-tools fs-1 text-info me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Maint. Bulan Ini</div>
                                <div class='fw-bold fs-2 text-info'>{$totalMaintenanceThisMonth}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        // Widget 3: Aset Rusak
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-danger h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-cone-striped fs-1 text-danger me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Aset Rusak</div>
                                <div class='fw-bold fs-2 text-danger'>{$assetsDamaged}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        // Widget 4: Aset Perlu Perbaikan (Maintenance Status)
        echo "<div class='col'>
                <div class='card card-neumorphic card-accent-warning h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-wrench-adjustable fs-1 text-warning me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Perlu Perbaikan</div>
                                <div class='fw-bold fs-2 text-warning'>{$assetsNeedRepair}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";

        echo "</div>"; // end row

        // Fetch detailed lists of Rusak and Maintenance assets
        $rusakAssets = $this->getAssetsByStatus('Rusak');
        $maintenanceAssets = $this->getAssetsByStatus('Maintenance');

        // Display Aset Rusak
        echo "<div class='row row-cols-1 row-cols-md-1 g-3 mt-3'>";
        echo "<div class='col'>";
        echo "<div class='card shadow mb-4'>";
        echo "<div class='card-header py-3 d-flex justify-content-between align-items-center'>";
        echo "<h6 class='m-0 font-weight-bold text-danger'>Daftar Aset Rusak</h6>";
        echo "</div>";
        echo "<div class='card-body'>";
        if (!empty($rusakAssets)) {
            echo "<div class='table-responsive'>";
            echo "<table class='table table-bordered' width='100%' cellspacing='0'>";
            echo "<thead><tr><th>Nama Perangkat</th><th>S/N</th><th>Lokasi</th><th>Aksi</th></tr></thead>";
            echo "<tbody>";
            foreach ($rusakAssets as $asset) {
                echo "<tr>";
                echo "<td>" . htmlspecialchars($asset['nama_perangkat']) . "</td>";
                echo "<td>" . htmlspecialchars($asset['serial_number']) . "</td>";
                echo "<td>" . htmlspecialchars($asset['lokasi']) . "</td>";
                echo "<td>
                        <form action='?page=mark_asset_repaired' method='POST' style='display:inline;'>
                            <input type='hidden' name='id_aset' value='" . htmlspecialchars($asset['id_aset']) . "'>
                            <input type='hidden' name='target_status' value='Aktif'>
                            <button type='submit' class='btn btn-success btn-sm' onclick=\"return confirm('Apakah Anda yakin aset ini sudah selesai diperbaiki dan akan diubah statusnya menjadi Aktif?')\">Selesai Diperbaiki</button>
                        </form>
                      </td>";
                echo "</tr>";
            }
            echo "</tbody>";
            echo "</table>";
            echo "</div>";
        } else {
            echo "<p>Tidak ada aset dengan status Rusak.</p>";
        }
        echo "</div>";
        echo "</div>";
        echo "</div>"; // end col
        echo "</div>"; // end row

        // Display Aset Perlu Perbaikan (Maintenance Status)
        echo "<div class='row row-cols-1 row-cols-md-1 g-3 mt-3'>";
        echo "<div class='col'>";
        echo "<div class='card shadow mb-4'>";
        echo "<div class='card-header py-3 d-flex justify-content-between align-items-center'>";
        echo "<h6 class='m-0 font-weight-bold text-warning'>Daftar Aset Perlu Perbaikan</h6>";
        echo "</div>";
        echo "<div class='card-body'>";
        if (!empty($maintenanceAssets)) {
            echo "<div class='table-responsive'>";
            echo "<table class='table table-bordered' width='100%' cellspacing='0'>";
            echo "<thead><tr><th>Nama Perangkat</th><th>S/N</th><th>Lokasi</th><th>Aksi</th></tr></thead>";
            echo "<tbody>";
            foreach ($maintenanceAssets as $asset) {
                echo "<tr>";
                echo "<td>" . htmlspecialchars($asset['nama_perangkat']) . "</td>";
                echo "<td>" . htmlspecialchars($asset['serial_number']) . "</td>";
                echo "<td>" . htmlspecialchars($asset['lokasi']) . "</td>";
                echo "<td>
                        <form action='?page=mark_asset_repaired' method='POST' style='display:inline;'>
                            <input type='hidden' name='id_aset' value='" . htmlspecialchars($asset['id_aset']) . "'>
                            <input type='hidden' name='target_status' value='Aktif'>
                            <button type='submit' class='btn btn-success btn-sm' onclick=\"return confirm('Apakah Anda yakin aset ini sudah selesai diperbaiki dan akan diubah statusnya menjadi Aktif?')\">Selesai Diperbaiki</button>
                        </form>
                      </td>";
                echo "</tr>";
            }
            echo "</tbody>";
            echo "</table>";
            echo "</div>";
        } else {
            echo "<p>Tidak ada aset dengan status Maintenance (Perlu Perbaikan).</p>";
        }
        echo "</div>";
        echo "</div>";
        echo "</div>"; // end col
        echo "</div>"; // end row

        // Fetch Tiket In Progress by Vendor
        $ticketsInProgressByVendor = $this->getTicketCountByStatus(['In Progress by Vendor']);

        // Widget: Tiket In Progress by Vendor (New Card)
        echo "<div class='row row-cols-1 row-cols-md-1 g-3 mt-3'>"; // New row for this specific KPI
        echo "<div class='col-md-6 col-lg-4'>
                <div class='card card-neumorphic card-accent-warning h-100'>
                    <div class='card-body'>
                        <div class='d-flex align-items-center justify-content-center'>
                            <i class='bi bi-hourglass-split fs-1 text-warning me-3'></i>
                            <div class='text-center'>
                                <div class='text-muted text-uppercase mb-1'>Tiket In Progress (Vendor)</div>
                                <div class='fw-bold fs-2 text-warning'>{$ticketsInProgressByVendor}</div>
                            </div>
                        </div>
                    </div>
                </div>
              </div>";
        echo "</div>"; // end new row

        // Add Scan Device button for petugas role
        if (isset($_SESSION['role']) && $_SESSION['role'] === 'petugas') {
            echo "<div class='row g-3 mt-3'>"; // Changed mt-4 to mt-3, added g-3 for consistent gap
            echo "<div class='col-12'>"; // Removed mb-4 for tighter spacing
            echo "<a href='?page=scan' class='btn btn-primary btn-lg'><i class='bi bi-qr-code-scan'></i> Scan Device</a>"; // Assuming Bootstrap Icons and a QR icon
            echo "</div>";
            echo "</div>";
        }


    }

    private function getAssetCount() {
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM assets");
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }

    private function getAssetCountByStatus($status) {
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM assets WHERE status_aset = ?");
        $stmt->bindParam(1, $status);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }

    private function getTicketCountByStatus(array $statuses) {
        $in = str_repeat('?,', count($statuses) - 1) . '?';
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM tickets WHERE status IN ($in)");
        $stmt->execute($statuses);
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }
    
    private function getOpenIncidentCount() {
        $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM sla_incidents WHERE waktu_selesai IS NULL");
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }

        private function getTotalMaintenanceCountByMonth($month, $year) {

            $start_date = date("Y-m-01", strtotime("$year-$month-01"));

            $end_date = date("Y-m-t", strtotime("$year-$month-01"));

    

            $stmt = $this->conn->prepare("SELECT COUNT(*) as count FROM maintenance_history WHERE tanggal_maintenance BETWEEN :start_date AND :end_date");

            $stmt->bindParam(':start_date', $start_date);

            $stmt->bindParam(':end_date', $end_date);

            $stmt->execute();

            return $stmt->fetch(PDO::FETCH_ASSOC)['count'];

        }

    

        private function getAssetsByStatus($status) {

            $asset = new Asset($this->conn); // Use the Asset model

            $stmt = $this->conn->prepare("SELECT id_aset, nama_perangkat, serial_number, lokasi, status_aset FROM assets WHERE status_aset = ? ORDER BY nama_perangkat ASC");

            $stmt->bindParam(1, $status);

            $stmt->execute();

            return $stmt->fetchAll(PDO::FETCH_ASSOC);

        }

    }

    
