<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

// Composer's autoloader
require_once dirname(__DIR__) . '/../vendor/autoload.php';

require_once dirname(__DIR__) . '/models/Helpdesk.php';
require_once dirname(__DIR__) . '/models/Asset.php';
require_once dirname(__DIR__) . '/models/User.php';
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 function showReportForm() {
        require_once dirname(__DIR__) . '/../views/helpdesk/report_form.php';
    }

    public function submitReport() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->helpdesk->category = $_POST['category'];
            $this->helpdesk->unit = $_POST['unit'];
            $this->helpdesk->reporter_name = $_POST['reporter_name'];
            $this->helpdesk->reporter_contact = $_POST['reporter_contact'];
            $this->helpdesk->problem_description = $_POST['problem_description'];
            $this->helpdesk->status = 'New';
            $this->helpdesk->priority = $_POST['priority'] ?? 'Medium';

            if (!filter_var($this->helpdesk->reporter_contact, FILTER_VALIDATE_EMAIL)) {
                header("Location: ?page=helpdesk_report_form&error=invalid_email");
                exit();
            }

            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();
            }
        }
    }

    public function index() {
        $this->helpdesk->markAllAsRead();

        $date_filter = $_GET['date_filter'] ?? '';
        $status_filter = $_GET['status_filter'] ?? '';
        $unit_filter = $_GET['unit_filter'] ?? '';

        // Pagination parameters
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1; // Use 'p' for page to avoid conflict with 'page' for routing
        $records_per_page = 10; // As requested

        // Calculate total number of rows for pagination
        $total_rows = $this->helpdesk->countAll($date_filter, $status_filter, $unit_filter);
        $total_pages = ceil($total_rows / $records_per_page);

        // Adjust current page if out of bounds
        if ($page < 1) $page = 1;
        if ($page > $total_pages && $total_pages > 0) $page = $total_pages;

        // Fetch tickets with filtering and pagination
        $tickets_stmt = $this->helpdesk->readAll($date_filter, $status_filter, $unit_filter, $page, $records_per_page);
        $tickets_raw = $tickets_stmt->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);
                $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;
        }

        $filters = [
            'date_filter' => $date_filter,
            'status_filter' => $status_filter,
            'unit_filter' => $unit_filter
        ];

        // Data to pass to view
        $view_data = [
            'tickets' => $tickets,
            'filters' => $filters,
            'page' => $page,
            'total_pages' => $total_pages,
            'total_rows' => $total_rows,
            'records_per_page' => $records_per_page
        ];

        extract($view_data); // Extract data to make it available in the view
        
        require_once dirname(__DIR__) . '/../views/helpdesk/index.php';
    }

    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;
        $users = $this->user->getAllUsers();
        $ticket_history = $this->helpdesk->getHistory($id_ticket);

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

    public function updateTicket() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $user_id_making_change = $_SESSION['user_id'] ?? null;
            $this->helpdesk->id_ticket = $_POST['id_ticket'];
            $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'];

            $current_ticket = new Helpdesk($this->conn);
            $current_ticket->id_ticket = $this->helpdesk->id_ticket;
            $current_ticket->readOne();

            $this->helpdesk->response_at = ('In Progress' === $this->helpdesk->status && null === $current_ticket->response_at)
                ? date('Y-m-d H:i:s')
                : $current_ticket->response_at;

            $this->helpdesk->resolved_at = (in_array($this->helpdesk->status, ['Resolved', 'Closed']) && null === $current_ticket->resolved_at)
                ? date('Y-m-d H:i:s')
                : $current_ticket->resolved_at;
            
            if ($this->helpdesk->update($user_id_making_change)) {
                // If status changed to Resolved or Closed, send an email.
                $is_newly_closed = in_array($this->helpdesk->status, ['Resolved', 'Closed']) && !in_array($current_ticket->status, ['Resolved', 'Closed']);
                
                if ($is_newly_closed) {
                    // Refresh data before sending
                    $this->helpdesk->readOne(); 
                    $this->sendClosureNotification($this->helpdesk);
                }

                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();
            }
        }
    }

    private function sendClosureNotification($ticket) {
        if (!filter_var($ticket->reporter_contact, FILTER_VALIDATE_EMAIL)) {
            return; // Don't try to send if the contact is not a valid email
        }

        $mail = new PHPMailer(true);

        try {
            // == Server settings - PENTING: ISI DETAIL INI ==
            // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Aktifkan untuk debugging
            $mail->isSMTP();
            $mail->Host       = 'rsjantungtasikmalaya.my.id'; // Ganti dengan server SMTP Anda
            $mail->SMTPAuth   = true;
            $mail->Username   = 'itrsjt@rsjantungtasikmalaya.my.id'; // Ganti dengan username SMTP
            $mail->Password   = 'Jantung2022';           // Ganti dengan password SMTP
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;
            // =================================================

            // Recipients
            $mail->setFrom('itrsjt@rsjantungtasikmalaya.my.id', 'Helpdesk IT'); // Ganti dengan alamat email "Dari"
            $mail->addAddress($ticket->reporter_contact, $ticket->reporter_name);

            // Content
            $mail->isHTML(true);
            $mail->Subject = "Update Tiket Helpdesk Anda #" . $ticket->id_ticket . ": " . $ticket->status;
            $mail->Body    = "
                <p>Halo " . htmlspecialchars($ticket->reporter_name) . ",</p>
                <p>Tiket helpdesk Anda dengan ID <strong>#" . htmlspecialchars($ticket->id_ticket) . "</strong> telah diperbarui statusnya menjadi <strong>" . htmlspecialchars($ticket->status) . "</strong>.</p>
                <p><strong>Deskripsi Masalah:</strong><br>" . nl2br(htmlspecialchars($ticket->problem_description)) . "</p>
                <p><strong>Detail Resolusi dari Petugas:</strong><br>" . nl2br(htmlspecialchars($ticket->resolution_details ?? 'Tidak ada detail resolusi.')) . "</p>
                <p>Terima kasih telah menggunakan layanan kami.</p>
                <p>---</p>
                <p><em>Ini adalah email otomatis, mohon untuk tidak membalas.</em></p>
            ";
            $mail->AltBody = "Halo " . $ticket->reporter_name . ",\n\nTiket helpdesk Anda #" . $ticket->id_ticket . " telah diperbarui statusnya menjadi " . $ticket->status . ".\n\nDetail Resolusi:\n" . ($ticket->resolution_details ?? 'Tidak ada detail resolusi.') . "\n\nTerima kasih.";

            $mail->send();
        } catch (Exception $e) {
            // Don't block the user, just log the error.
            // In a real app, you'd use a proper logger.
            error_log("Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
        }
    }

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

        $date_filter = $_GET['date_filter'] ?? '';
        $status_filter = $_GET['status_filter'] ?? '';
        $unit_filter = $_GET['unit_filter'] ?? '';

        $tickets_stmt = $this->helpdesk->readAll($date_filter, $status_filter, $unit_filter);
        $tickets = $tickets_stmt->fetchAll(PDO::FETCH_ASSOC);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="helpdesk_report_' . date('Ymd_His') . '.csv"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, ['ID Tiket', 'Kategori', 'Unit', 'Pelapor', 'Deskripsi Masalah', 'Prioritas', 'Status', 'Dibuat Pada', 'Terakhir Diperbarui', 'Waktu Respons', 'Waktu Selesai', 'Detail Resolusi', 'Ditugaskan ke'], ';');
        
        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);
    }

    public function getUnreadCount() {
        header('Content-Type: application/json');
        if (!isset($_SESSION['user_id'])) {
            echo json_encode(['error' => 'Unauthorized']);
            exit();
        }
        echo json_encode(['unread_count' => $this->helpdesk->countUnread()]);
        exit();
    }
}