<?php

class Slide {
    private $pdo;
    private string $uploadDir;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
        $this->uploadDir = __DIR__ . '/../uploads/slides/';
        // Ensure upload directory exists
        if (!is_dir($this->uploadDir) && !mkdir($this->uploadDir, 0775, true) && !is_dir($this->uploadDir)) {
            throw new RuntimeException('Unable to create slides upload directory.');
        }
    }

    /**
     * Adds a new slide to the database.
     *
     * @param string $title_en The English title of the slide.
     * @param string $description The full description of the slide.
     * @param string $photoname The filename of the uploaded photo.
     * @param int $reg_by The ID of the user who registered the slide.
     * @param int $fkisp_id_of The person ID of the user who registered the slide.
     * @return bool True on success, false on failure.
     * @throws Exception If a database error occurs.
     */
    public function addSlide(string $title_en, string $description, string $photoname, int $reg_by, int $fkisp_id_of): bool {
        $sql = "INSERT INTO dsps_tbl_dspsslide (dspsslide_title_en, dspsslide_description, dspsslide_photoname, dspsslide_reg_by, fkisp_id_of)
                VALUES (:title_en, :description, :photoname, :reg_by, :fkisp_id_of)";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':title_en', $title_en);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':photoname', $photoname);
            $stmt->bindParam(':reg_by', $reg_by, PDO::PARAM_INT);
            $stmt->bindParam(':fkisp_id_of', $fkisp_id_of, PDO::PARAM_INT);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error adding slide: " . $e->getMessage());
            throw new Exception("Could not add slide. Please try again later.");
        }
    }

    /**
     * Updates an existing slide in the database.
     *
     * @param int $id The ID of the slide to update.
     * @param string $title_en The new English title.
     * @param string $description The new description.
     * @param string $photoname The new filename of the photo.
     * @param int $mod_by The ID of the user who modified the slide.
     * @param int $fkisp_id_of The person ID of the user who modified the slide.
     * @return bool True on success, false on failure.
     * @throws Exception If a database error occurs.
     */
    public function updateSlide(int $id, string $title_en, string $description, string $photoname, int $mod_by, int $fkisp_id_of): bool {
        $sql = "UPDATE dsps_tbl_dspsslide
                SET dspsslide_title_en = :title_en, dspsslide_description = :description, dspsslide_photoname = :photoname,
                    dspsslide_mod_datetime = CURRENT_TIMESTAMP, dspsslide_reg_by = :mod_by, fkisp_id_of = :fkisp_id_of
                WHERE pkdspsslide_id = :id";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':title_en', $title_en);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':photoname', $photoname);
            $stmt->bindParam(':mod_by', $mod_by, PDO::PARAM_INT);
            $stmt->bindParam(':fkisp_id_of', $fkisp_id_of, PDO::PARAM_INT);
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error updating slide (ID: $id): " . $e->getMessage());
            throw new Exception("Could not update slide. Please try again later.");
        }
    }

    /**
     * Deletes a slide from the database and its associated photo file.
     *
     * @param int $id The ID of the slide to delete.
     * @return bool True on success, false on failure.
     * @throws Exception If a database error occurs.
     */
    public function deleteSlide(int $id): bool {
        // First, get the photo path to delete the file
        $slide = $this->getSlideById($id);
        if ($slide && !empty($slide['dspsslide_photoname'])) {
            $filePath = $this->uploadDir . $slide['dspsslide_photoname'];
            if (file_exists($filePath)) {
                unlink($filePath); // Delete the file
            }
        }

        $sql = "DELETE FROM dsps_tbl_dspsslide WHERE pkdspsslide_id = :id";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error deleting slide (ID: $id): " . $e->getMessage());
            throw new Exception("Could not delete slide. Please try again later.");
        }
    }

    /**
     * Retrieves a single slide by its ID.
     *
     * @param int $id The ID of the slide.
     * @return array|false The slide data as an associative array, or false if not found.
     * @throws Exception If a database error occurs.
     */
    public function getSlideById(int $id) {
        $sql = "SELECT * FROM dsps_tbl_dspsslide WHERE pkdspsslide_id = :id";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error fetching slide by ID ($id): " . $e->getMessage());
            throw new Exception("Could not retrieve slide. Please try again later.");
        }
    }

    /**
     * Retrieves all slides.
     *
     * @return array An array of slide data.
     * @throws Exception If a database error occurs.
     */
    public function getAllSlides(): array {
        $sql = "SELECT * FROM dsps_tbl_dspsslide ORDER BY pkdspsslide_id ASC"; // Order by ID or a custom sort order
        try {
            $stmt = $this->pdo->query($sql);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error fetching all slides: " . $e->getMessage());
            throw new Exception("Could not retrieve slides. Please try again later.");
        }
    }

    /**
     * Gets the total count of slides.
     *
     * @return int The total number of slides.
     * @throws Exception If a database error occurs.
     */
    public function getTotalSlides(): int {
        $sql = "SELECT COUNT(*) FROM dsps_tbl_dspsslide";
        try {
            $stmt = $this->pdo->query($sql);
            return $stmt->fetchColumn();
        } catch (PDOException $e) {
            error_log("Error getting total slides count: " . $e->getMessage());
            throw new Exception("Could not retrieve slide count. Please try again later.");
        }
    }

    /**
     * Handles the upload of a slide photo.
     *
     * @param array $file The $_FILES array for the uploaded photo.
     * @return string The unique filename of the uploaded photo.
     * @throws Exception If the upload fails or file type is invalid.
     */
    public function handlePhotoUpload(array $file): string {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload error: ' . $file['error']);
        }

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);

        if (!in_array($mimeType, $allowedTypes)) {
            throw new Exception('Invalid file type. Only JPEG, PNG, and GIF images are allowed.');
        }

        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $uniqueFilename = uniqid('slide_') . '.' . $extension;
        $destination = $this->uploadDir . $uniqueFilename;

        if (!move_uploaded_file($file['tmp_name'], $destination)) {
            throw new Exception('Failed to move uploaded file.');
        }

        return $uniqueFilename;
    }
}
