<?php

use chillerlan\QRCode\QRCode;

require_once dirname(__DIR__) . '/models/Asset.php';
require_once dirname(__DIR__) . '/../config/db.php'; // Correct path to db.php

class AssetController {
    private $conn;
    private $asset;

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

    public function index() {
        // Display list of assets
        $stmt = $this->asset->read();
        $num = $stmt->rowCount();

        echo "<div class='d-flex justify-content-between align-items-center mb-3'>";
        echo "<h2>Daftar Aset IT</h2>";
        echo "<div>"; // Group buttons
        echo "<a href='?page=add_asset' class='btn btn-primary me-2'>Tambah Aset Baru</a>";
        echo "<a href='?page=print_all_qrcodes' class='btn btn-info' target='_blank'><i class='bi bi-qr-code me-2'></i> Print All QR Codes</a>";
        echo "</div>"; // End group buttons
        echo "</div>";

        if ($num > 0) {
            echo "<div class='table-responsive'>";
            echo "<table class='table table-striped table-bordered table-hover'>";
            echo "<thead class='table-dark'>
                    <tr>
                        <th>ID</th>
                        <th>Nama Perangkat</th>
                        <th>Kategori</th>
                        <th>S/N</th>
                        <th>Lokasi</th>
                        <th>PIC</th>
                        <th>Tgl Pembelian</th>
                        <th>Status</th>
                        <th>QR Code</th>
                        <th>Aksi</th>
                        <th>Edit</th> <!-- New Column -->
                    </tr>
                  </thead>";
            echo "<tbody>";
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                extract($row);
                echo "<tr>";
                echo "<td>" . htmlspecialchars($id_aset) . "</td>";
                echo "<td>" . htmlspecialchars($nama_perangkat) . "</td>";
                echo "<td>" . htmlspecialchars($kategori) . "</td>";
                echo "<td>" . htmlspecialchars($serial_number) . "</td>";
                echo "<td>" . htmlspecialchars($lokasi) . "</td>";
                echo "<td>" . htmlspecialchars($pic) . "</td>";
                echo "<td>" . htmlspecialchars($tanggal_pembelian) . "</td>";
                
                $status_badge = 'secondary';
                if ($status_aset == 'Aktif') $status_badge = 'success';
                if ($status_aset == 'Rusak') $status_badge = 'danger';
                if ($status_aset == 'Maintenance') $status_badge = 'warning';

                echo "<td><span class='badge bg-{$status_badge}'>" . htmlspecialchars($status_aset) . "</span></td>";
                
                // Display QR Code
                if (!empty($qr_code)) {
                    echo "<td><img src='{$qr_code}' alt='QR Code for asset {$id_aset}' style='width: 75px; height: 75px;'></td>";
                } else {
                    echo "<td>(Belum ada)</td>";
                }
                echo "<td>
                        <a href='?page=maintenance&id=" . htmlspecialchars($id_aset) . "' class='btn btn-info btn-sm me-1'>Lihat History</a>
                    </td>";
                echo "<td>
                        <a href='?page=edit_asset&id=" . htmlspecialchars($id_aset) . "' class='btn btn-warning btn-sm'>Edit</a>
                    </td>"; // New Edit Button
                echo "</tr>";
            }
            echo "</tbody>";
            echo "</table>";
            echo "</div>";
        } else {
            echo "<div class='alert alert-info'>Tidak ada aset yang ditemukan. Silakan <a href='?page=add_asset'>tambah aset baru</a>.</div>";
        }
    }

    public function create() {
        // Display asset creation form
        echo "<h2>Tambah Aset Baru</h2>";
        echo "<form action='?page=add_asset_process' method='POST' class='needs-validation' novalidate>";
        
        echo "<div class='row'>";
        
        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='nama_perangkat' class='form-label'>Nama Perangkat:</label>";
        echo "<input type='text' class='form-control' id='nama_perangkat' name='nama_perangkat' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='kategori' class='form-label'>Kategori:</label>";
        echo "<select class='form-select' id='kategori' name='kategori' required>";
        $categories = ['PC', 'Laptop', 'Printer', 'Switch', 'Server', 'Monitor', 'Lain-lain'];
        foreach ($categories as $cat) {
            echo "<option value='{$cat}'>{$cat}</option>";
        }
        echo "</select>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='serial_number' class='form-label'>Serial Number:</label>";
        echo "<input type='text' class='form-control' id='serial_number' name='serial_number' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='lokasi' class='form-label'>Lokasi:</label>";
        echo "<input type='text' class='form-control' id='lokasi' name='lokasi' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='pic' class='form-label'>PIC:</label>";
        echo "<input type='text' class='form-control' id='pic' name='pic' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='tanggal_pembelian' class='form-label'>Tanggal Pembelian:</label>";
        echo "<input type='date' class='form-control' id='tanggal_pembelian' name='tanggal_pembelian' required>";
        echo "</div>";

        echo "<div class='col-md-4 mb-3'>";
        echo "<label for='nilai_pembelian' class='form-label'>Nilai Pembelian (Rp):</label>";
        echo "<input type='number' class='form-control' id='nilai_pembelian' name='nilai_pembelian' step='0.01' required>";
        echo "</div>";
        
        echo "<div class='col-md-4 mb-3'>";
        echo "<label for='life_cycle_years' class='form-label'>Life Cycle (Tahun):</label>";
        echo "<input type='number' class='form-control' id='life_cycle_years' name='life_cycle_years' required>";
        echo "</div>";
        
        echo "<div class='col-md-4 mb-3'>";
        echo "<label for='status_aset' class='form-label'>Status Awal:</label>";
        echo "<select class='form-select' id='status_aset' name='status_aset' required>";
        $st = ['Aktif', 'Rusak', 'Dismantle', 'Maintenance'];
        foreach ($st as $s) {
            echo "<option value='{$s}'>{$s}</option>";
        }
        echo "</select>";
        echo "</div>";

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

        echo "<button type='submit' class='btn btn-primary mt-3'>Simpan Aset</button>";
        echo "</form>";
    }

    public function processCreate() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            // Set asset property values from form
            $this->asset->nama_perangkat = $_POST['nama_perangkat'];
            $this->asset->kategori = $_POST['kategori'];
            $this->asset->serial_number = $_POST['serial_number'];
            $this->asset->lokasi = $_POST['lokasi'];
            $this->asset->pic = $_POST['pic'];
            $this->asset->tanggal_pembelian = $_POST['tanggal_pembelian'];
            $this->asset->nilai_pembelian = $_POST['nilai_pembelian'];
            $this->asset->life_cycle_years = $_POST['life_cycle_years'];
            $this->asset->status_aset = $_POST['status_aset'];

            if ($this->asset->create()) {
                // Now that we have the ID, generate QR code and update the asset
                $newId = $this->asset->id_aset;
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                $host = $_SERVER['HTTP_HOST'];
                $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
                
                // Data for QR code, pointing to the helpdesk report form
                $qrData = "{$protocol}://{$host}{$uri}?page=helpdesk_report_form&asset_id={$newId}";
                
                // Generate QR code as data URI
                $qrCodeDataUri = (new QRCode)->render($qrData);
                
                // Update the asset with the QR code
                $this->asset->id_aset = $newId;
                $this->asset->qr_code = $qrCodeDataUri;
                
                if ($this->asset->update()) {
                    echo "<div class='alert alert-success'>Aset berhasil ditambahkan beserta QR Code! <a href='?page=assets'>Lihat daftar aset</a>.</div>";
                } else {
                    // This is less likely to happen but good to handle
                    echo "<div class='alert alert-warning'>Aset berhasil dibuat, tetapi gagal menyimpan QR Code.</div>";
                }

            } else {
                echo "<div class='alert alert-danger'>Gagal menambahkan aset. Pastikan Serial Number unik.</div>";
            }
        } else {
            echo "<div class='alert alert-warning'>Permintaan tidak valid.</div>";
        }
    }

    public function edit() {
        $id_aset = $_GET['id'] ?? die('ERROR: Missing Asset ID.');

        $this->asset->id_aset = $id_aset;
        $this->asset->readOne(); // Method to read single asset details

        echo "<h2>Edit Aset: " . htmlspecialchars($this->asset->nama_perangkat) . "</h2>";
        // This will be a form similar to create(), but pre-filled
        echo "<form action='?page=edit_asset_process' method='POST' class='needs-validation' novalidate>";
        echo "<input type='hidden' name='id_aset' value='" . htmlspecialchars($this->asset->id_aset) . "'>";
        
        echo "<div class='row'>";
        
        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='nama_perangkat' class='form-label'>Nama Perangkat:</label>";
        echo "<input type='text' class='form-control' id='nama_perangkat' name='nama_perangkat' value='" . htmlspecialchars($this->asset->nama_perangkat) . "' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='kategori' class='form-label'>Kategori:</label>";
        echo "<select class='form-select' id='kategori' name='kategori' required>";
        $categories = ['PC', 'Laptop', 'Printer', 'Switch', 'Server', 'Monitor', 'Lain-lain'];
        foreach ($categories as $cat) {
            $selected = ($this->asset->kategori == $cat) ? 'selected' : '';
            echo "<option value='{$cat}' {$selected}>{$cat}</option>";
        }
        echo "</select>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='serial_number' class='form-label'>Serial Number:</label>";
        echo "<input type='text' class='form-control' id='serial_number' name='serial_number' value='" . htmlspecialchars($this->asset->serial_number) . "' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='lokasi' class='form-label'>Lokasi:</label>";
        echo "<input type='text' class='form-control' id='lokasi' name='lokasi' value='" . htmlspecialchars($this->asset->lokasi) . "' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='pic' class='form-label'>PIC:</label>";
        echo "<input type='text' class='form-control' id='pic' name='pic' value='" . htmlspecialchars($this->asset->pic) . "' required>";
        echo "</div>";

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='tanggal_pembelian' class='form-label'>Tanggal Pembelian:</label>";
        echo "<input type='date' class='form-control' id='tanggal_pembelian' name='tanggal_pembelian' value='" . htmlspecialchars($this->asset->tanggal_pembelian) . "' required>";
        echo "</div>";

        echo "<div class='col-md-4 mb-3'>";
        echo "<label for='nilai_pembelian' class='form-label'>Nilai Pembelian (Rp):</label>";
        echo "<input type='number' class='form-control' id='nilai_pembelian' name='nilai_pembelian' step='0.01' value='" . htmlspecialchars($this->asset->nilai_pembelian) . "' required>";
        echo "</div>";
        
        echo "<div class='col-md-4 mb-3'>";
        echo "<label for='life_cycle_years' class='form-label'>Life Cycle (Tahun):</label>";
        echo "<input type='number' class='form-control' id='life_cycle_years' name='life_cycle_years' value='" . htmlspecialchars($this->asset->life_cycle_years) . "' required>";
        echo "</div>";
        
        echo "<div class='col-md-4 mb-3'>";
        echo "<label for='status_aset' class='form-label'>Status Awal:</label>";
        echo "<select class='form-select' id='status_aset' name='status_aset' required>";
        $st = ['Aktif', 'Rusak', 'Dismantle', 'Maintenance'];
        foreach ($st as $s) {
            $selected = ($this->asset->status_aset == $s) ? 'selected' : '';
            echo "<option value='{$s}' {$selected}>{$s}</option>";
        }
        echo "</select>";
        echo "</div>";

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

        echo "<button type='submit' class='btn btn-primary mt-3'>Update Aset</button>";
        echo "</form>";
    }

    public function processEdit() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $this->asset->id_aset = $_POST['id_aset'];
            $this->asset->nama_perangkat = $_POST['nama_perangkat'];
            $this->asset->kategori = $_POST['kategori'];
            $this->asset->serial_number = $_POST['serial_number'];
            $this->asset->lokasi = $_POST['lokasi'];
            $this->asset->pic = $_POST['pic'];
            $this->asset->tanggal_pembelian = $_POST['tanggal_pembelian'];
            $this->asset->nilai_pembelian = $_POST['nilai_pembelian'];
            $this->asset->life_cycle_years = $_POST['life_cycle_years'];
            $this->asset->status_aset = $_POST['status_aset'];

            if ($this->asset->update()) {
                echo "<div class='alert alert-success'>Aset berhasil diperbarui! <a href='?page=assets'>Lihat daftar aset</a>.</div>";
            } else {
                echo "<div class='alert alert-danger'>Gagal memperbarui aset.</div>";
            }
        } else {
            echo "<div class='alert alert-warning'>Permintaan tidak valid.</div>";
        }
    }

    public function printAllQRCodes() {
        // Fetch all assets
        $stmt = $this->asset->read();
        $assets = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // This view will contain the HTML structure for printing QR codes
        // It will loop through $assets and display each QR code
        require_once dirname(__DIR__) . '/../views/assets/print_all_qrcodes.php';
    }
}
