<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/Attachment.php';

$database = new Database();
$db = $database->getConnection();

$attachment = new Attachment($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $attachment->id = $_GET['id'];
            $attachment->readOne();
            
            if($attachment->item_id != null) {
                $attachment_arr = array(
                    "id" => $attachment->id,
                    "item_id" => $attachment->item_id,
                    "filename" => $attachment->filename,
                    "original_name" => $attachment->original_name,
                    "file_type" => $attachment->file_type,
                    "file_path" => $attachment->file_path,
                    "file_size" => $attachment->file_size,
                    "mime_type" => $attachment->mime_type,
                    "created_at" => $attachment->created_at
                );
                
                http_response_code(200);
                echo json_encode($attachment_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Attachment not found."));
            }
        } elseif(isset($_GET['item_id'])) {
            $attachment->item_id = $_GET['item_id'];
            $stmt = $attachment->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $attachments_arr = array();
                $attachments_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $attachment_item = array(
                        "id" => $id,
                        "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
                    );
                    
                    array_push($attachments_arr["records"], $attachment_item);
                }
                
                http_response_code(200);
                echo json_encode($attachments_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Missing item_id parameter."));
        }
        break;
        
    case 'POST':
        if(isset($_FILES['attachment']) && isset($_POST['item_id']) && isset($_POST['file_type'])) {
            $item_id = $_POST['item_id'];
            $file_type = $_POST['file_type'];
            
            $result = $attachment->uploadFile($_FILES['attachment'], $item_id, $file_type);
            
            if($result['success']) {
                http_response_code(201);
                echo json_encode(array(
                    "message" => "Attachment uploaded successfully.",
                    "id" => $result['id'],
                    "url" => $result['url']
                ));
            } else {
                http_response_code(400);
                echo json_encode(array("message" => $result['message']));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Missing required parameters."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $attachment->id = $_GET['id'];
            
            if($attachment->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Attachment was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete attachment."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete attachment. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
