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

include_once 'db_connect.php';

$method = $_SERVER['REQUEST_METHOD'];

// 1. GET: Fetch all documents
if ($method == 'GET') {
    $query = "SELECT * FROM documents ORDER BY upload_date DESC";
    $result = $conn->query($query);
    
    $docs = [];
    while($row = $result->fetch_assoc()) {
        $docs[] = [
            "id" => $row['id'],
            "title" => $row['title'],
            "category" => $row['category'],
            "url" => $row['file_path'],
            "size" => $row['file_size'],
            "date" => date("M d, Y", strtotime($row['upload_date']))
        ];
    }
    echo json_encode(["success" => true, "data" => $docs]);
}

// 2. POST: Create or Update Document Entry (With File Cleanup on Update)
if ($method == 'POST') {
    $data = json_decode(file_get_contents("php://input"));
    
    if (!empty($data->title) && !empty($data->url)) {
        $title = mysqli_real_escape_string($conn, $data->title);
        $category = mysqli_real_escape_string($conn, $data->category);
        $url = mysqli_real_escape_string($conn, $data->url); // This is the new file path
        $size = mysqli_real_escape_string($conn, $data->size);

        if (isset($data->id) && $data->id > 0) {
            // UPDATE LOGIC
            $id = intval($data->id);

            // A. Fetch current file path from DB to check for changes
            $stmt = $conn->prepare("SELECT file_path FROM documents WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $res = $stmt->get_result();
            $old_doc = $res->fetch_assoc();

            // B. If the file path has changed, delete the old file from the server
            if ($old_doc && !empty($old_doc['file_path']) && $old_doc['file_path'] !== $url) {
                $old_file_path = ".." . $old_doc['file_path']; // Prepends ".." to target root from /api folder
                if (file_exists($old_file_path)) {
                    unlink($old_file_path);
                }
            }

            $query = "UPDATE documents SET title='$title', category='$category', file_path='$url', file_size='$size' WHERE id=$id";
        } else {
            // INSERT LOGIC
            $query = "INSERT INTO documents (title, category, file_path, file_size) VALUES ('$title', '$category', '$url', '$size')";
        }

        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Document record saved and old files cleaned."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    }
}

// 3. DELETE: Remove Document Entry & Physically Delete File
if ($method == 'DELETE') {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id > 0) {
        // A. Fetch the file path BEFORE deleting the database record
        $stmt = $conn->prepare("SELECT file_path FROM documents WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $doc = $res->fetch_assoc();

        if ($doc && !empty($doc['file_path'])) {
            $file_to_delete = ".." . $doc['file_path'];
            
            // B. Physically delete the file if it exists
            if (file_exists($file_to_delete)) {
                unlink($file_to_delete);
            }
        }

        // C. Delete the record from the database
        $query = "DELETE FROM documents WHERE id = $id";
        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Document record and file deleted."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Invalid ID provided."]);
    }
}

$conn->close();
?>