<?php
require_once dirname(__DIR__) . '/models/Helpdesk.php';
require_once dirname(__DIR__) . '/models/Asset.php'; // To get asset details for forms/views
require_once dirname(__DIR__) . '/models/User.php';  // To get users for assigning tickets
require_once dirname(__DIR__) . '/../config/db.php';

class HelpdeskController {
    private $conn;
    private $helpdesk;
    private $asset;
    private $user;

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

    // Public form for reporting a problem (no login required)
    public function showReportForm() {
        require_once dirname(__DIR__) . '/../views/helpdesk/report_form.php';
    }

    // Process public problem report submission
    public function submitReport() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->helpdesk->category = $_POST['category']; // New
            $this->helpdesk->unit = $_POST['unit']; // New
            $this->helpdesk->reporter_name = $_POST['reporter_name'];
            // $this->helpdesk->reporter_contact is removed
            $this->helpdesk->problem_description = $_POST['problem_description'];
            $this->helpdesk->status = 'New';
            $this->helpdesk->priority = $_POST['priority'] ?? 'Medium'; // Default to Medium

            // Basic validation for new fields and removed contact
            if (empty($this->helpdesk->category) || empty($this->helpdesk->unit) || empty($this->helpdesk->reporter_name) || empty($this->helpdesk->problem_description)) {
                header("Location: ?page=helpdesk_report_form&error=empty_fields");
                exit();
            }

            if ($this->helpdesk->create()) {
                header("Location: ?page=helpdesk_report_form&message=report_success");
                exit();
            } else {
                header("Location: ?page=helpdesk_report_form&error=submit_failed");
                exit();
            }
        }
    }

    // Internal staff view: List all helpdesk tickets
    public function index() {
        // Retrieve filter parameters from GET request
        $date_filter = $_GET['date_filter'] ?? '';
        $status_filter = $_GET['status_filter'] ?? '';
        $unit_filter = $_GET['unit_filter'] ?? '';

        // Pass filters to the model's readAll method
        $tickets_raw = $this->helpdesk->readAll($date_filter, $status_filter, $unit_filter)->fetchAll(PDO::FETCH_ASSOC);

        $tickets = [];
        foreach ($tickets_raw as $ticket) {
            $created = new DateTime($ticket['created_at']);
            $response_time_str = 'N/A';
            if ($ticket['response_at']) {
                $responded = new DateTime($ticket['response_at']);
                $interval = $created->diff($responded);
                // Format the interval nicely, e.g., "1d 2h 30m"
                $parts = [];
                if ($interval->d > 0) $parts[] = $interval->d . ' hari';
                if ($interval->h > 0) $parts[] = $interval->h . ' jam';
                if ($interval->i > 0) $parts[] = $interval->i . ' menit';
                
                if (empty($parts)) {
                    $response_time_str = 'Kurang dari 1 menit';
                } else {
                    $response_time_str = implode(' ', $parts);
                }
            }
            $ticket['response_time'] = $response_time_str;
            $tickets[] = $ticket;
        }

        // Pass filter values to the view for pre-filling the form
        $filters = [
            'date_filter' => $date_filter,
            'status_filter' => $status_filter,
            'unit_filter' => $unit_filter
        ];

        require_once dirname(__DIR__) . '/../views/helpdesk/index.php';
    }

    // Internal staff view: View and update a specific ticket
    public function viewTicket() {
        $id_ticket = $_GET['id'] ?? null;
        if (!$id_ticket) {
            header("Location: ?page=helpdesk_tickets&error=ticket_id_missing");
            exit();
        }

        $this->helpdesk->id_ticket = $id_ticket;
        if (!$this->helpdesk->readOne()) {
            header("Location: ?page=helpdesk_tickets&error=ticket_not_found");
            exit();
        }
        $ticket_data = $this->helpdesk;

        // Fetch users for assignment dropdown
        $users = $this->user->getAllUsers(); // Assuming User model has this

        require_once dirname(__DIR__) . '/../views/helpdesk/view.php';
    }

    // Internal staff action: Update ticket status, assignment, etc.
    public function updateTicket() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->helpdesk->id_ticket = $_POST['id_ticket'];
            // Fetch current ticket data to preserve existing non-updated fields
            $current_ticket = new Helpdesk($this->conn);
            $current_ticket->id_ticket = $_POST['id_ticket'];
            $current_ticket->readOne();

            $this->helpdesk->status = $_POST['status'];
            $this->helpdesk->priority = $_POST['priority'];
            $this->helpdesk->assigned_to_user_id = $_POST['assigned_to_user_id'] !== '' ? $_POST['assigned_to_user_id'] : null;
            $this->helpdesk->resolution_details = $_POST['resolution_details'];

            // Handle response_at
            if ($this->helpdesk->status === 'In Progress' && $current_ticket->response_at === null) {
                $this->helpdesk->response_at = date('Y-m-d H:i:s');
            } else {
                $this->helpdesk->response_at = $current_ticket->response_at; // Keep existing response_at
            }

            // Handle resolved_at
            if ($this->helpdesk->status === 'Resolved' && $current_ticket->resolved_at === null) {
                $this->helpdesk->resolved_at = date('Y-m-d H:i:s');
            } else {
                $this->helpdesk->resolved_at = $current_ticket->resolved_at; // Keep existing resolved_at
            }
            
            if ($this->helpdesk->update()) {
                header("Location: ?page=helpdesk_view_ticket&id=" . $this->helpdesk->id_ticket . "&message=update_success");
                exit();
            } else {
                header("Location: ?page=helpdesk_view_ticket&id=" . $this->helpdesk->id_ticket . "&error=update_failed");
                exit();
            }
        }
    }

    public function downloadReport() {
        if (!isset($_SESSION['user_id']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'petugas')) {
            header("Location: ?page=login"); // Or unauthorized page
            exit();
        }

        // Retrieve filter parameters from GET request
        $date_filter = $_GET['date_filter'] ?? '';
        $status_filter = $_GET['status_filter'] ?? '';
        $unit_filter = $_GET['unit_filter'] ?? '';

        // Fetch tickets using the same filters as the index view
        $tickets_stmt = $this->helpdesk->readAll($date_filter, $status_filter, $unit_filter);
        $tickets = $tickets_stmt->fetchAll(PDO::FETCH_ASSOC);

        // Prepare CSV headers
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="helpdesk_report_' . date('Ymd_His') . '.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');

        $output = fopen('php://output', 'w');

        // Output CSV header row
        fputcsv($output, [
            'ID Tiket', 'Kategori', 'Unit', 'Pelapor', 'Deskripsi Masalah', 
            'Prioritas', 'Status', 'Dibuat Pada', 'Terakhir Diperbarui', 
            'Waktu Respons', 'Waktu Selesai', 'Detail Resolusi', 'Ditugaskan ke'
        ]);

        // Output data rows
        foreach ($tickets as $ticket) {
            fputcsv($output, [
                $ticket['id_ticket'],
                $ticket['category'],
                $ticket['unit'],
                $ticket['reporter_name'],
                $ticket['problem_description'],
                $ticket['priority'],
                $ticket['status'],
                date('d-m-Y H:i', strtotime($ticket['created_at'])),
                date('d-m-Y H:i', strtotime($ticket['updated_at'])),
                $ticket['response_at'] ? date('d-m-Y H:i', strtotime($ticket['response_at'])) : '',
                $ticket['resolved_at'] ? date('d-m-Y H:i', strtotime($ticket['resolved_at'])) : '',
                $ticket['resolution_details'],
                $ticket['assigned_to_name']
            ]);
        }

        fclose($output);
        exit();
    }
}