<?php
require_once dirname(__DIR__) . '/models/ProductRelease.php';
require_once dirname(__DIR__) . '/../config/db.php';

class ProductReleaseController {
    private $conn;
    private $productRelease;

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

    public function index() {
        $stmt = $this->productRelease->read();
        $num = $stmt->rowCount();

        echo "<h2>Product Releases</h2>";
        echo "<p>Modul ini berisi semua file PDF terkait rilis produk atau fitur yang sudah diimplementasikan.</p>";
        echo "<button type='button' class='btn btn-primary mb-3' data-bs-toggle='modal' data-bs-target='#uploadPdfModal'>
                <i class='bi bi-upload me-2'></i> Upload PDF Baru
              </button>";

        // Modal for PDF Upload
        echo "<div class='modal fade' id='uploadPdfModal' tabindex='-1' aria-labelledby='uploadPdfModalLabel' aria-hidden='true'>
                <div class='modal-dialog'>
                    <div class='modal-content'>
                        <form action='?page=product_release_upload' method='POST' enctype='multipart/form-data'>
                            <div class='modal-header'>
                                <h5 class='modal-title' id='uploadPdfModalLabel'>Upload Product Release PDF</h5>
                                <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button>
                            </div>
                            <div class='modal-body'>
                                <div class='mb-3'>
                                    <label for='title' class='form-label'>Judul:</label>
                                    <input type='text' class='form-control' name='title' required>
                                </div>
                                <div class='mb-3'>
                                    <label for='description' class='form-label'>Deskripsi:</label>
                                    <textarea class='form-control' name='description' rows='3'></textarea>
                                </div>
                                <div class='mb-3'>
                                    <label for='pdf_file' class='form-label'>Pilih file PDF (.pdf):</label>
                                    <input class='form-control' type='file' name='pdf_file' accept='.pdf' required>
                                </div>
                            </div>
                            <div class='modal-footer'>
                                <button type='button' class='btn btn-secondary' data-bs-dismiss='modal'>Batal</button>
                                <button type='submit' class='btn btn-primary'>Upload</button>
                            </div>
                        </form>
                    </div>
                </div>
              </div>";

        if ($num > 0) {
            echo "<div class='list-group'>";
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                extract($row);
                $filePath = 'uploads/product_releases/' . basename($file_path);
                echo "<div class='list-group-item list-group-item-action d-flex justify-content-between align-items-center'>";
                echo "    <div>";
                echo "        <h5 class='mb-1'>" . htmlspecialchars($title) . "</h5>";
                echo "        <p class='mb-1'>" . htmlspecialchars($description) . "</p>";
                echo "        <small>Uploaded on: " . date("d M Y, H:i", strtotime($created_at)) . "</small>";
                echo "    </div>";
                echo "    <div>";
                echo "        <a href='" . htmlspecialchars($filePath) . "' class='btn btn-success btn-sm' target='_blank'><i class='bi bi-eye me-1'></i> Lihat PDF</a>";
                echo "        <a href='?page=product_release_delete&id=" . htmlspecialchars($id) . "' class='btn btn-danger btn-sm' onclick='return confirm(\"Apakah Anda yakin ingin menghapus file ini?\")'><i class='bi bi-trash'></i></a>";
                echo "    </div>";
                echo "</div>";
            }
            echo "</div>";
        } else {
            echo "<div class='alert alert-info'>Belum ada product release yang diunggah.</div>";
        }
    }

    public function upload() {
        if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["pdf_file"])) {
            $target_dir = "uploads/product_releases/";
            // Create directory if it doesn't exist
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }

            $target_file = $target_dir . basename($_FILES["pdf_file"]["name"]);
            $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

            // Check if file is a PDF
            if ($file_type != "pdf") {
                echo "<div class='alert alert-danger'>Error: Hanya file PDF yang diizinkan.</div>";
                echo "<a href='?page=product_releases' class='btn btn-secondary'>Kembali</a>";
                return;
            }

            // Move uploaded file
            if (move_uploaded_file($_FILES["pdf_file"]["tmp_name"], $target_file)) {
                $this->productRelease->title = $_POST['title'];
                $this->productRelease->description = $_POST['description'];
                $this->productRelease->file_path = basename($_FILES["pdf_file"]["name"]);

                if ($this->productRelease->create()) {
                     header("Location: ?page=product_releases&message=upload_success");
                } else {
                    echo "<div class='alert alert-danger'>Gagal menyimpan data ke database.</div>";
                }
            } else {
                echo "<div class='alert alert-danger'>Terjadi error saat mengunggah file.</div>";
            }
        } else {
             header("Location: ?page=product_releases&error=invalid_request");
        }
        exit();
    }

    public function delete() {
        if (isset($_GET['id'])) {
            $this->productRelease->id = $_GET['id'];
            // Here you might want to also delete the file from the server
            // For simplicity, we'll just delete the DB record for now.
            if ($this->productRelease->delete()) {
                header("Location: ?page=product_releases&message=delete_success");
            } else {
                header("Location: ?page=product_releases&error=delete_failed");
            }
        } else {
            header("Location: ?page=product_releases&error=missing_id");
        }
        exit();
    }
}
