<?php
session_start();
header('Content-Type: application/json');
require_once '../../config/config.php';

// Check if user is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    // Validate input
    if (empty($_POST['title']) || empty($_POST['category']) || !isset($_FILES['file'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }
    
    $title = trim($_POST['title']);
    $description = trim($_POST['description'] ?? '');
    $category = $_POST['category'];
    $is_public = isset($_POST['is_public']) ? 1 : 0;
    $uploaded_by = $_SESSION['admin_id'];
    
    // File validation
    $file = $_FILES['file'];
    $maxFileSize = 10 * 1024 * 1024; // 10MB
    $allowedExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'jpeg', 'png', 'gif'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'File upload error']);
        exit();
    }
    
    if ($file['size'] > $maxFileSize) {
        echo json_encode(['success' => false, 'message' => 'File size exceeds 10MB limit']);
        exit();
    }
    
    $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($fileExtension, $allowedExtensions)) {
        echo json_encode(['success' => false, 'message' => 'File type not allowed']);
        exit();
    }
    
    // Create upload directory if it doesn't exist
    $uploadDir = '../../uploads/documents/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Generate unique filename
    $fileName = uniqid() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file['name']);
    $filePath = $uploadDir . $fileName;
    
    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $filePath)) {
        echo json_encode(['success' => false, 'message' => 'Failed to save file']);
        exit();
    }
    
    // Connect to database
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Insert document record
    $stmt = $pdo->prepare("
        INSERT INTO documents (title, description, file_name, file_path, file_size, file_type, category, uploaded_by, is_public)
        VALUES (:title, :description, :file_name, :file_path, :file_size, :file_type, :category, :uploaded_by, :is_public)
    ");
    
    $stmt->execute([
        'title' => $title,
        'description' => $description,
        'file_name' => $file['name'],
        'file_path' => $filePath,
        'file_size' => $file['size'],
        'file_type' => $file['type'],
        'category' => $category,
        'uploaded_by' => $uploaded_by,
        'is_public' => $is_public
    ]);
    
    $documentId = $pdo->lastInsertId();
    
    // Log activity
    $logStmt = $pdo->prepare("
        INSERT INTO activity_logs (user_id, action, details, entity_type, entity_id)
        VALUES (:user_id, 'document_upload', :details, 'document', :entity_id)
    ");
    
    $logStmt->execute([
        'user_id' => $uploaded_by,
        'details' => "Uploaded document: $title",
        'entity_id' => $documentId
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Document uploaded successfully',
        'document_id' => $documentId
    ]);
    
} catch (Exception $e) {
    // Clean up file if database insert failed
    if (isset($filePath) && file_exists($filePath)) {
        unlink($filePath);
    }
    
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
