<?php
// api/uploads.php
require_once '../config/database.php';
require_once __DIR__ . '/session_auth.php';
rvu_audit_context_from_request($pdo);
header("Content-Type: application/json");

// Define absolute path for the uploads folder in XAMPP
$upload_dir = '../uploads/';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            http_response_code(400);
            echo json_encode(["detail" => "No file uploaded or upload error"]);
            exit;
        }

        $chat_id = $_POST['chat_id'] ?? '';
        $sender = $_POST['sender'] ?? '';

        // Generate unique filename
        $file_info = pathinfo($_FILES['file']['name']);
        $file_extension = $file_info['extension'] ?? '';
        $unique_filename = md5(uniqid('', true)) . '.' . $file_extension;
        $target_path = $upload_dir . $unique_filename;

        // Save physical file
        if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
            // Create URL (Adjust the base URL if needed for your local network)
            $base_url = "http://127.0.0.1/skill_backend";
            $file_url = "$base_url/uploads/$unique_filename";

            // Save record to DB
            $stmt = $pdo->prepare("INSERT INTO chat_attachments (chat_id, sender_email, file_name, file_type, file_url, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$chat_id, $sender, $_FILES['file']['name'], $file_extension, $file_url]);

            echo json_encode([
                "message" => "Upload successful",
                "file_url" => $file_url
            ]);
        } else {
            http_response_code(500);
            echo json_encode(["detail" => "Failed to move uploaded file"]);
        }
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["detail" => $e->getMessage()]);
}
?>