<?php

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

class TicketController {
    private $conn;
    private $ticket;

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

    // List all tickets
    public function index() {
        echo "<div class='d-flex justify-content-between align-items-center mb-3'>";
        echo "<h2>Daftar Tiket (Request ke Vendor)</h2>";
        echo "<a href='?page=add_ticket' class='btn btn-primary'>Buat Tiket Baru</a>";
        echo "</div>";

        $stmt = $this->ticket->read();
        $num = $stmt->rowCount();

        if ($num > 0) {
            echo "<div class='table-responsive'>";
            echo "<table class='table table-bordered table-hover'>";
            echo "<thead class='table-dark'><tr><th>ID</th><th>Subjek</th><th>Vendor/Sistem</th><th>Prioritas</th><th>Status</th><th>Requester</th><th>Tanggal Dibuat</th><th>Aksi</th></tr></thead>";
            echo "<tbody>";
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                extract($row);
                echo "<tr>";
                echo "<td>#{$id_ticket}</td>";
                echo "<td>" . htmlspecialchars($subject) . "</td>";
                echo "<td>" . htmlspecialchars($vendor_system) . "</td>";
                echo "<td>" . htmlspecialchars($priority) . "</td>";
                echo "<td><span class='badge bg-info'>" . htmlspecialchars($status) . "</span></td>";
                echo "<td>" . htmlspecialchars($requester) . "</td>";
                echo "<td>" . htmlspecialchars($created_at) . "</td>";
                echo "<td><a href='?page=view_ticket&id={$id_ticket}' class='btn btn-sm btn-outline-primary'>Lihat</a></td>";
                echo "</tr>";
            }
            echo "</tbody></table></div>";
        } else {
            echo "<div class='alert alert-info'>Belum ada tiket yang dibuat.</div>";
        }
    }

    // View a single ticket and its updates
    public function view() {
        if (!isset($_GET['id'])) {
            echo "<div class='alert alert-danger'>ID Tiket tidak ditemukan.</div>";
            return;
        }
        $this->ticket->id_ticket = $_GET['id'];
        if (!$this->ticket->readOne()) {
            echo "<div class='alert alert-danger'>Tiket tidak ditemukan.</div>";
            return;
        }

        echo "<h3>#" . htmlspecialchars($this->ticket->id_ticket) . ": " . htmlspecialchars($this->ticket->subject) . "</h3>";
        echo "<div class='card mb-4'><div class='card-body'>";
        echo "<p><strong>Vendor/Sistem:</strong> " . htmlspecialchars($this->ticket->vendor_system) . "</p>";
        echo "<p><strong>Tipe Request:</strong> " . htmlspecialchars($this->ticket->request_type) . "</p>";
        echo "<p><strong>Status:</strong> <span class='badge bg-info'>" . htmlspecialchars($this->ticket->status) . "</span></p>";
        echo "<p><strong>Prioritas:</strong> " . htmlspecialchars($this->ticket->priority) . "</p>";
        echo "<hr><strong>Deskripsi:</strong><br>" . nl2br(htmlspecialchars($this->ticket->description));
        echo "</div></div>";
        
        // --- Updates ---
        echo "<h4>Riwayat Update</h4>";
        $updatesStmt = $this->ticket->getUpdates();
        if ($updatesStmt->rowCount() > 0) {
            echo "<ul class='list-group mb-4'>";
            while ($row = $updatesStmt->fetch(PDO::FETCH_ASSOC)) {
                echo "<li class='list-group-item'>";
                echo nl2br(htmlspecialchars($row['update_description']));
                echo "<footer class='blockquote-footer mt-2'>Oleh <strong>" . htmlspecialchars($row['updated_by']) . "</strong> pada " . $row['created_at'] . "</footer>";
                echo "</li>";
            }
            echo "</ul>";
        } else {
            echo "<p>Belum ada update.</p>";
        }

        // --- Add Update Form ---
        echo "<h4>Tambah Update / Komentar</h4>";
        echo "<form action='?page=add_ticket_update' method='POST'>";
        echo "<input type='hidden' name='id_ticket' value='" . $this->ticket->id_ticket . "'>";
        echo "<div class='mb-3'><textarea name='update_description' class='form-control' rows='4' required></textarea></div>";
        echo "<div class='mb-3'><input type='text' name='updated_by' class='form-control' placeholder='Nama Anda' required></div>";
        echo "<div class='mb-3'><label class='form-label'>Ubah Status (Opsional)</label><select name='new_status' class='form-select'><option value=''>-- Jangan Ubah --</option>";
        $statuses = ['Submitted', 'In Progress by Vendor', 'Ready for Testing', 'Done', 'On Hold'];
        foreach ($statuses as $s) { echo "<option value='{$s}'>{$s}</option>"; }
        echo "</select></div>";
        echo "<button type='submit' class='btn btn-success'>Simpan Update</button>";
        echo "</form>";
    }

    // Display form to create a new ticket
    public function create() {
        echo "<h2>Buat Tiket Baru untuk Vendor</h2>";
        echo "<form action='?page=add_ticket_process' method='POST' class='needs-validation' novalidate>";
        echo "<div class='row'>";
        echo "<div class='col-md-6 mb-3'><label class='form-label'>Vendor/Sistem</label><input type='text' name='vendor_system' class='form-control' required></div>";
        echo "<div class='col-md-6 mb-3'><label class='form-label'>Tipe Request</label><select name='request_type' class='form-select' required>";
        $types = ['Penambahan Fitur', 'Laporan Bug/Error', 'Integrasi Sistem', 'Perubahan Konfigurasi'];
        foreach ($types as $t) { echo "<option value='{$t}'>{$t}</option>"; }
        echo "</select></div>";
        echo "<div class='col-12 mb-3'><label class='form-label'>Subjek</label><input type='text' name='subject' class='form-control' required></div>";
        echo "<div class='col-12 mb-3'><label class='form-label'>Deskripsi Detail</label><textarea name='description' class='form-control' rows='6' required></textarea></div>";
        echo "<div class='col-md-6 mb-3'><label class='form-label'>Prioritas</label><select name='priority' class='form-select'>";
        $priorities = ['Low', 'Medium', 'High', 'Critical'];
        foreach ($priorities as $p) { echo "<option value='{$p}'>{$p}</option>"; }
        echo "</select></div>";
        echo "<div class='col-md-6 mb-3'><label class='form-label'>Nama Anda (Requester)</label><input type='text' name='requester' class='form-control' required></div>";
        echo "</div>";
        echo "<button type='submit' class='btn btn-primary'>Buat Tiket</button>";
        echo "</form>";
    }

    // Process new ticket creation
    public function processCreate() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $this->ticket->vendor_system = $_POST['vendor_system'];
            $this->ticket->request_type = $_POST['request_type'];
            $this->ticket->subject = $_POST['subject'];
            $this->ticket->description = $_POST['description'];
            $this->ticket->priority = $_POST['priority'];
            $this->ticket->requester = $_POST['requester'];
            $this->ticket->status = 'Submitted';

            if ($this->ticket->create()) {
                echo "<div class='alert alert-success'>Tiket baru berhasil dibuat! <a href='?page=tickets'>Lihat semua tiket</a>.</div>";
            } else {
                echo "<div class='alert alert-danger'>Gagal membuat tiket.</div>";
            }
        }
    }
    
    // Process ticket update
    public function processUpdate() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $id_ticket = $_POST['id_ticket'];
            $update_description = $_POST['update_description'];
            $updated_by = $_POST['updated_by'];
            $new_status = $_POST['new_status'];
            
            $this->ticket->addUpdate($id_ticket, $update_description, $updated_by);
            if (!empty($new_status)) {
                $this->ticket->updateStatus($id_ticket, $new_status);
            }
            
            echo "<div class='alert alert-success'>Update berhasil ditambahkan! <a href='?page=view_ticket&id={$id_ticket}'>Kembali ke tiket</a>.</div>";
        }
    }
}
