<?php

use chillerlan\QRCode\QRCode;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

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() {
        // Search and pagination variables
        $keywords = isset($_GET['s']) ? $_GET['s'] : '';
        // Validate page number, using 'p_num' to avoid conflict with 'page' route parameter
        $page_num = isset($_GET['p_num']) && is_numeric($_GET['p_num']) && $_GET['p_num'] > 0 ? (int)$_GET['p_num'] : 1;
        $records_per_page = 10;
        $from_record_num = ($records_per_page * $page_num) - $records_per_page;

        // Fetch paginated assets
        $stmt = $this->asset->readPaging($keywords, $from_record_num, $records_per_page);
        $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 me-2' target='_blank'><i class='bi bi-qr-code me-2'></i> Print All QR Codes</a>";
        echo "<button type='button' class='btn btn-success' data-bs-toggle='modal' data-bs-target='#uploadExcelModal'><i class='bi bi-file-earmark-excel me-2'></i> Upload Excel</button>";
        echo "</div>"; // End group buttons
        echo "</div>"; // End d-flex

        // Search form
        echo "<form action='' method='get' class='mb-4'>";
        echo "<input type='hidden' name='page' value='assets'>"; // Keep this for routing
        echo "<div class='input-group'>";
        echo "<input type='text' name='s' class='form-control' placeholder='Cari berdasarkan nama, kategori, S/N, atau lokasi...' value='" . htmlspecialchars($keywords, ENT_QUOTES) . "'>";
        echo "<button class='btn btn-primary' type='submit'>Cari</button>";
        echo "</div>";
        echo "</form>";

        // Modal for Excel Upload (same as before)
        echo "<div class='modal fade' id='uploadExcelModal' tabindex='-1' aria-labelledby='uploadExcelModalLabel' aria-hidden='true'>...</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>
                        <th>Hapus</th>
                    </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>";
                
                if (!empty($qr_code)) {
                    echo "<td><img src='{$qr_code}' alt='QR Code' 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'>Lihat History</a></td>";
                echo "<td><a href='?page=edit_asset&id=" . htmlspecialchars($id_aset) . "' class='btn btn-warning btn-sm'>Edit</a></td>";
                echo "<td><a href='?page=delete_asset&id=" . htmlspecialchars($id_aset) . "' class='btn btn-danger btn-sm' onclick='return confirm(\"Yakin?\")'>Hapus</a></td>";
                echo "</tr>";
            }
            echo "</tbody>";
            echo "</table>";
            echo "</div>";

            // Pagination
            $total_rows = $this->asset->count($keywords);
            // The 'page' param is for the router, 'p_num' is for pagination
            $page_url = "?page=assets&s=" . urlencode($keywords); 
            $page = $page_num; // Rename for compatibility with pagination.php
            include_once 'pagination.php';

        } else {
            echo "<div class='alert alert-info'>Tidak ada aset yang ditemukan.</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;
                // Data for QR code, pointing to the maintenance form
                $qrData = BASE_URL . "?page=maintenance_form&id_aset={$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 delete() {
        if (!isset($_GET['id'])) {
            header("Location: ?page=assets&error=missing_id");
            exit();
        }

        $this->asset->id_aset = $_GET['id'];

        if ($this->asset->delete()) {
            header("Location: ?page=assets&message=delete_success");
        } else {
            header("Location: ?page=assets&error=delete_failed");
        }
        exit();
    }

    public function markAssetAsRepaired() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $id_aset = $_POST['id_aset'] ?? null;
            $target_status = $_POST['target_status'] ?? 'Aktif'; // Default to Aktif

            if (!$id_aset) {
                header("Location: ?page=home&error=missing_asset_id");
                exit();
            }

            if ($this->asset->updateStatus($id_aset, $target_status)) {
                header("Location: ?page=home&message=asset_repaired_success");
            } else {
                header("Location: ?page=home&error=asset_repaired_failed");
            }
            exit();
        } else {
            header("Location: ?page=home&error=invalid_request");
            exit();
        }
    }

    public function uploadExcel() {
        if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["excel_file"]) && $_FILES["excel_file"]["error"] == UPLOAD_ERR_OK) {
            $file_name = $_FILES["excel_file"]["tmp_name"];

            try {
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name);
                $worksheet = $spreadsheet->getActiveSheet();
                $highestRow = $worksheet->getHighestRow();

                $uploadedCount = 0;
                $failedCount = 0;
                $errors = [];

                // Assuming the first row is the header
                // Expected columns: Nama Perangkat, Kategori, S/N, Lokasi, PIC, Tgl Pembelian, Nilai Pembelian, Life Cycle (Tahun), Status Awal
                $header = [];
                foreach ($worksheet->getRowIterator(1, 1) as $row) { // Read only the first row
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(TRUE);
                    foreach ($cellIterator as $cell) {
                        $header[] = $cell->getValue();
                    }
                }

                $expectedHeaders = [
                    'Nama Perangkat', 'Kategori', 'S/N', 'Lokasi', 'PIC',
                    'Tgl Pembelian', 'Nilai Pembelian', 'Life Cycle (Tahun)', 'Status Awal'
                ];

                // Basic header validation
                if (count(array_diff($expectedHeaders, $header)) > 0) {
                     echo "<div class='alert alert-danger'>Format header Excel tidak sesuai. Pastikan ada kolom: " . implode(', ', $expectedHeaders) . "</div>";
                     echo "<a href='?page=assets' class='btn btn-primary'>Kembali ke Daftar Aset</a>";
                     return;
                }
                
                // Map header names to database column names (or model properties)
                $columnMap = [
                    'Nama Perangkat' => 'nama_perangkat',
                    'Kategori' => 'kategori',
                    'S/N' => 'serial_number',
                    'Lokasi' => 'lokasi',
                    'PIC' => 'pic',
                    'Tgl Pembelian' => 'tanggal_pembelian',
                    'Nilai Pembelian' => 'nilai_pembelian',
                    'Life Cycle (Tahun)' => 'life_cycle_years',
                    'Status Awal' => 'status_aset'
                ];


                for ($row = 2; $row <= $highestRow; ++$row) {
                    $rowData = [];
                    foreach ($header as $colIndex => $colName) {
                        $columnLetter = Coordinate::stringFromColumnIndex($colIndex + 1);
                        $cellValue = $worksheet->getCell($columnLetter . $row)->getValue();
                        $dbColName = $columnMap[$colName] ?? null;
                        if ($dbColName) {
                            $rowData[$dbColName] = $cellValue;
                        }
                    }

                    // Simple validation for required fields (customize as needed)
                    if (empty($rowData['nama_perangkat']) || empty($rowData['serial_number'])) {
                        $errors[] = "Baris {$row}: 'Nama Perangkat' atau 'S/N' kosong. Data dilewati.";
                        $failedCount++;
                        continue;
                    }

                    // Assign data to asset model
                    $this->asset->nama_perangkat = $rowData['nama_perangkat'];
                    $this->asset->kategori = $rowData['kategori'];
                    $this->asset->serial_number = $rowData['serial_number'];
                    $this->asset->lokasi = $rowData['lokasi'];
                    $this->asset->pic = $rowData['pic'];
                    $this->asset->tanggal_pembelian = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowData['tanggal_pembelian'])->format('Y-m-d');
                    $this->asset->nilai_pembelian = $rowData['nilai_pembelian'];
                    $this->asset->life_cycle_years = $rowData['life_cycle_years'];
                    $this->asset->status_aset = $rowData['status_aset'];

                    // Attempt to create asset
                    if ($this->asset->create()) {
                        $newId = $this->asset->id_aset;
                        $qrData = BASE_URL . "?page=maintenance_form&id_aset={$newId}";
                        $qrCodeDataUri = (new QRCode)->render($qrData);
                        
                        $this->asset->id_aset = $newId;
                        $this->asset->qr_code = $qrCodeDataUri;
                        
                        if ($this->asset->update()) { // Update with QR code
                            $uploadedCount++;
                        } else {
                            $errors[] = "Baris {$row} (SN: {$rowData['serial_number']}): Gagal memperbarui QR Code setelah membuat aset.";
                            $failedCount++;
                        }
                    } else {
                        $errors[] = "Baris {$row} (SN: {$rowData['serial_number']}): Gagal menambahkan aset. Serial Number mungkin sudah ada atau data tidak valid.";
                        $failedCount++;
                    }
                }

                echo "<div class='alert alert-success'>Proses upload selesai. Berhasil mengunggah {$uploadedCount} aset.</div>";
                if ($failedCount > 0) {
                    echo "<div class='alert alert-warning'>{$failedCount} aset gagal diunggah:</div>";
                    echo "<ul>";
                    foreach ($errors as $error) {
                        echo "<li>" . htmlspecialchars($error) . "</li>";
                    }
                    echo "</ul>";
                }
                echo "<a href='?page=assets' class='btn btn-primary'>Kembali ke Daftar Aset</a>";

            } catch (\Exception $e) {
                echo "<div class='alert alert-danger'>Error saat memproses file Excel: " . htmlspecialchars($e->getMessage()) . "</div>";
                echo "<a href='?page=assets' class='btn btn-primary'>Kembali ke Daftar Aset</a>";
            }
        } else {
            echo "<div class='alert alert-warning'>Tidak ada file Excel yang diunggah atau terjadi kesalahan.</div>";
            echo "<a href='?page=assets' class='btn btn-primary'>Kembali ke Daftar Aset</a>";
        }
    }

    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';
    }

    public function regenerateAllQRCodes() {
        echo "<html><head><title>Regenerating QR Codes</title>";
        echo "<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css' rel='stylesheet'>";
        echo "<style>body { padding: 20px; font-family: sans-serif; }</style>";
        echo "</head><body><div class='container'>";
        echo "<h1>Regenerating All Asset QR Codes...</h1>";
        
        // Ensure BASE_URL is available
        if (!defined('BASE_URL')) {
            echo "<p class='alert alert-danger'>Error: BASE_URL is not defined. Cannot generate correct URLs.</p>";
            echo "</div></body></html>";
            return;
        }

        $stmt = $this->asset->read(); // Get all assets
        $assets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $successCount = 0;
        $failureCount = 0;

        foreach ($assets as $asset) {
            $assetId = $asset['id_aset'];
            
            // Generate the correct URL for the maintenance form
            $qrData = BASE_URL . "?page=maintenance_form&id_aset=" . $assetId;
            
            // Generate QR code as data URI
            $qrCodeDataUri = (new QRCode)->render($qrData);

            // Set properties on the model and update
            $this->asset->id_aset = $assetId;
            $this->asset->qr_code = $qrCodeDataUri;

            if ($this->asset->updateQrCode()) {
                echo "<p class='text-success'>Successfully updated QR Code for Asset ID: {$assetId}</p>";
                $successCount++;
            } else {
                echo "<p class='text-danger'>Failed to update QR Code for Asset ID: {$assetId}</p>";
                $failureCount++;
            }
        }

        echo "<h2 class='mt-4'>Regeneration Complete!</h2>";
        echo "<div class='alert alert-info'>";
        echo "    <p>{$successCount} QR Codes updated successfully.</p>";
        echo "    <p>{$failureCount} QR Codes failed to update.</p>";
        echo "</div>";
        echo "<a href='?page=assets' class='btn btn-primary'>Back to Asset List</a>";
        echo "</div></body></html>";
    }
}
