<?php
class Attachment {
    private $conn;
    private $table_name = "attachments";

    public $id;
    public $item_id;
    public $filename;
    public $original_name;
    public $file_type;
    public $file_path;
    public $file_size;
    public $mime_type;
    public $created_at;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function create() {
        $query = "INSERT INTO " . $this->table_name . " SET item_id=:item_id, filename=:filename, original_name=:original_name, file_type=:file_type, file_path=:file_path, file_size=:file_size, mime_type=:mime_type, created_at=:created_at";

        $stmt = $this->conn->prepare($query);

        $this->item_id = htmlspecialchars(strip_tags($this->item_id));
        $this->filename = htmlspecialchars(strip_tags($this->filename));
        $this->original_name = htmlspecialchars(strip_tags($this->original_name));
        $this->file_type = htmlspecialchars(strip_tags($this->file_type));
        $this->file_path = htmlspecialchars(strip_tags($this->file_path));
        $this->file_size = htmlspecialchars(strip_tags($this->file_size));
        $this->mime_type = htmlspecialchars(strip_tags($this->mime_type));
        $this->created_at = date('Y-m-d H:i:s');

        $stmt->bindParam(":item_id", $this->item_id);
        $stmt->bindParam(":filename", $this->filename);
        $stmt->bindParam(":original_name", $this->original_name);
        $stmt->bindParam(":file_type", $this->file_type);
        $stmt->bindParam(":file_path", $this->file_path);
        $stmt->bindParam(":file_size", $this->file_size);
        $stmt->bindParam(":mime_type", $this->mime_type);
        $stmt->bindParam(":created_at", $this->created_at);

        if($stmt->execute()) {
            return true;
        }

        return false;
    }

    public function read() {
        $query = "SELECT * FROM " . $this->table_name . " WHERE item_id = ? ORDER BY created_at DESC";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->item_id);
        $stmt->execute();

        return $stmt;
    }

    public function readOne() {
        $query = "SELECT * FROM " . $this->table_name . " WHERE id = ? LIMIT 0,1";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->id);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $this->item_id = $row['item_id'];
        $this->filename = $row['filename'];
        $this->original_name = $row['original_name'];
        $this->file_type = $row['file_type'];
        $this->file_path = $row['file_path'];
        $this->file_size = $row['file_size'];
        $this->mime_type = $row['mime_type'];
        $this->created_at = $row['created_at'];
    }

    public function delete() {
        $query = "SELECT file_path FROM " . $this->table_name . " WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->id);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if($row && file_exists($row['file_path'])) {
            unlink($row['file_path']);
        }

        $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->id);

        if($stmt->execute()) {
            return true;
        }

        return false;
    }

    public function uploadFile($file, $item_id, $file_type) {
        $uploadDir = '/var/www/html/uploads/';
        $allowedTypes = [
            'application/pdf',
            'image/jpeg',
            'image/png',
            'image/gif',
            'text/plain',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];
        $maxFileSize = 10 * 1024 * 1024; // 10MB

        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        if (!in_array($file['type'], $allowedTypes)) {
            return ['success' => false, 'message' => 'Invalid file type.'];
        }

        if ($file['size'] > $maxFileSize) {
            return ['success' => false, 'message' => 'File too large. Maximum size is 10MB.'];
        }

        $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $uniqueFileName = uniqid() . '.' . $fileExtension;
        $uploadPath = $uploadDir . $uniqueFileName;

        if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
            $this->item_id = $item_id;
            $this->filename = $uniqueFileName;
            $this->original_name = $file['name'];
            $this->file_type = $file_type;
            $this->file_path = $uniqueFileName;
            $this->file_size = $file['size'];
            $this->mime_type = $file['type'];

            if ($this->create()) {
                // Use relative URL to avoid mixed content warnings
                $fullUrl = '/uploads/' . $uniqueFileName;
                
                return ['success' => true, 'url' => $fullUrl, 'id' => $this->conn->lastInsertId()];
            } else {
                unlink($uploadPath);
                return ['success' => false, 'message' => 'Failed to save attachment record.'];
            }
        } else {
            return ['success' => false, 'message' => 'Failed to upload file.'];
        }
    }
}
?>
