<?php
// models/ReportMedia.php

/**
 * ReportMedia Model for Rehlko Customer Care application.
 * Manages CRUD operations and data interaction for the 'report_media' table.
 */
class ReportMedia {
    private $conn;
    private $table_name = "report_media";

    // Object properties
    public $id;
    public $report_index;
    public $media_type;
    public $media_path;
    public $media_name;

    /**
     * Constructor for the ReportMedia model.
     *
     * @param mysqli $db The database connection object.
     */
    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * Uploads media and creates a new record in the report_media table.
     *
     * @param array $file The $_FILES array entry for the uploaded file.
     * @param string $reportIndex The report index to associate the media with.
     * @param string $mediaType The type of media ('image' or 'video').
     * @return array|false An array with media details on success, false on failure.
     */
    public function uploadMedia($file, $reportIndex, $mediaType) {
        $uploadDir = __DIR__ . '/../public/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true); // Create directory if it doesn't exist
        }

        $originalFileName = basename($file['name']);
        $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
        $newFileName = uniqid('media_') . '.' . $fileExtension;
        $targetFilePath = $uploadDir . $newFileName;
        $mediaPathForDb = 'public/uploads/' . $newFileName; // Path relative to public/api

        // Validate file type
        $allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $allowedVideoTypes = ['video/mp4', 'video/webm', 'video/ogg'];

        if ($mediaType === 'image' && !in_array($file['type'], $allowedImageTypes)) {
            error_log("Invalid image file type: " . $file['type']);
            return false;
        }
        if ($mediaType === 'video' && !in_array($file['type'], $allowedVideoTypes)) {
            error_log("Invalid video file type: " . $file['type']);
            return false;
        }

        if (move_uploaded_file($file['tmp_name'], $targetFilePath)) {
            $query = "INSERT INTO " . $this->table_name . "
                      SET report_index=?, media_type=?, media_path=?, media_name=?";

            $stmt = $this->conn->prepare($query);
            if ($stmt === false) {
                error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
                // Clean up uploaded file if DB insert fails
                unlink($targetFilePath);
                return false;
            }

            // Sanitize inputs
            $reportIndex = htmlspecialchars(strip_tags($reportIndex));
            $mediaType = htmlspecialchars(strip_tags($mediaType));
            $mediaPathForDb = htmlspecialchars(strip_tags($mediaPathForDb));
            $originalFileName = htmlspecialchars(strip_tags($originalFileName));

            $stmt->bind_param("ssss", $reportIndex, $mediaType, $mediaPathForDb, $originalFileName);

            if ($stmt->execute()) {
                return [
                    'id' => $this->conn->insert_id,
                    'report_index' => $reportIndex,
                    'media_type' => $mediaType,
                    'media_path' => $mediaPathForDb,
                    'media_name' => $originalFileName
                ];
            } else {
                error_log("Media record insertion failed: (" . $stmt->errno . ") " . $stmt->error);
                // Clean up uploaded file if DB insert fails
                unlink($targetFilePath);
                return false;
            }
        } else {
            error_log("Failed to move uploaded file: " . $file['error']);
            return false;
        }
    }

    /**
     * Reads media records associated with a specific report index.
     *
     * @param string $reportIndex The report index.
     * @return array An array of media records.
     */
    public function readByReportIndex($reportIndex) {
        $query = "SELECT id, report_index, media_type, media_path, media_name
                  FROM " . $this->table_name . "
                  WHERE report_index = ?";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
            return [];
        }

        $reportIndex = htmlspecialchars(strip_tags($reportIndex));
        $stmt->bind_param("s", $reportIndex);

        if ($stmt->execute()) {
            $result = $stmt->get_result();
            $media = [];
            while ($row = $result->fetch_assoc()) {
                $media[] = $row;
            }
            return $media;
        }
        error_log("Read media by report index failed: (" . $stmt->errno . ") " . $stmt->error);
        return [];
    }

    /**
     * Deletes a media record by ID and its associated file.
     *
     * @param int $id The ID of the media record to delete.
     * @return bool True on success, false on failure.
     */
    public function delete($id) {
        // First, get the file path from the database
        $query = "SELECT media_path FROM " . $this->table_name . " WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed for delete media (select path): (" . $this->conn->errno . ") " . $this->conn->error);
            return false;
        }
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();

        if ($row) {
            $filePath = __DIR__ . '/../public/' . $row['media_path']; // Full path to the file

            // Delete the database record
            $deleteQuery = "DELETE FROM " . $this->table_name . " WHERE id = ?";
            $deleteStmt = $this->conn->prepare($deleteQuery);
            if ($deleteStmt === false) {
                error_log("Prepare failed for delete media (delete record): (" . $this->conn->errno . ") " . $this->conn->error);
                return false;
            }
            $deleteStmt->bind_param("i", $id);

            if ($deleteStmt->execute()) {
                // If DB record deleted, attempt to delete the file
                if (file_exists($filePath)) {
                    if (unlink($filePath)) {
                        return true;
                    } else {
                        error_log("Failed to delete media file: " . $filePath);
                        return false; // DB record deleted, but file failed
                    }
                }
                return true; // DB record deleted, file didn't exist or wasn't found
            } else {
                error_log("Media record deletion failed: (" . $deleteStmt->errno . ") " . $deleteStmt->error);
                return false;
            }
        }
        error_log("Media record not found for ID: " . $id);
        return false;
    }
}
?>
