<?php
/**
 * AJAX Upload Handler
 * Video Portal Management System
 */

require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

header('Content-Type: application/json');

// Check if user is admin
if (!isLoggedIn() || !isAdmin()) {
    writeLog("AJAX Upload: Unauthorized access attempt from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

writeLog("AJAX Upload: Started by user " . ($_SESSION['username'] ?? 'unknown'), 'INFO');

// Check if file was uploaded
if (!isset($_FILES['video_file']) || $_FILES['video_file']['error'] !== UPLOAD_ERR_OK) {
    $errorMessages = [
        UPLOAD_ERR_INI_SIZE => 'File exceeds server maximum size (upload_max_filesize: ' . ini_get('upload_max_filesize') . ')',
        UPLOAD_ERR_FORM_SIZE => 'File exceeds form maximum size',
        UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder (upload_tmp_dir: ' . (ini_get('upload_tmp_dir') ?: sys_get_temp_dir()) . ')',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
        UPLOAD_ERR_EXTENSION => 'Upload stopped by PHP extension'
    ];
    
    $errorCode = isset($_FILES['video_file']) ? $_FILES['video_file']['error'] : UPLOAD_ERR_NO_FILE;
    $errorMsg = $errorMessages[$errorCode] ?? 'Unknown upload error (code: ' . $errorCode . ')';
    
    writeLog("AJAX Upload failed: " . $errorMsg);
    echo json_encode(['success' => false, 'error' => $errorMsg]);
    exit;
}

// Upload directory
$uploadDir = __DIR__ . '/../assets/uploads/videos';

// Create directory if not exists
if (!file_exists($uploadDir)) {
    writeLog("AJAX Upload: Creating directory {$uploadDir}", 'INFO');
    if (!@mkdir($uploadDir, 0755, true)) {
        $error = error_get_last();
        writeLog("AJAX Upload failed: Could not create directory - " . ($error['message'] ?? 'Unknown error'));
        echo json_encode(['success' => false, 'error' => 'Failed to create upload directory']);
        exit;
    }
    // Set directory permissions on Windows
    setWindowsPermissions($uploadDir);
}

// Check if directory is writable
if (!is_writable($uploadDir)) {
    writeLog("AJAX Upload failed: Directory not writable - {$uploadDir}");
    echo json_encode(['success' => false, 'error' => 'Upload directory is not writable: ' . $uploadDir]);
    exit;
}

// Allowed file types
$allowedTypes = ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm', 'zip', 'rar'];

// Get file info
$file = $_FILES['video_file'];
$fileName = $file['name'];
$fileSize = $file['size'];
$fileTmp = $file['tmp_name'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

writeLog("AJAX Upload: Processing '{$fileName}' (Size: " . round($fileSize/1024/1024, 2) . "MB, Type: {$fileExt})", 'INFO');

// Validate file type
if (!in_array($fileExt, $allowedTypes)) {
    writeLog("AJAX Upload failed for '{$fileName}': Invalid file type '{$fileExt}'");
    echo json_encode(['success' => false, 'error' => 'Invalid file type: ' . $fileExt . '. Allowed: ' . implode(', ', $allowedTypes)]);
    exit;
}

// Validate file size (100MB max)
$maxSize = 100 * 1024 * 1024;
if ($fileSize > $maxSize) {
    writeLog("AJAX Upload failed for '{$fileName}': File too large (" . round($fileSize/1024/1024, 2) . "MB)");
    echo json_encode(['success' => false, 'error' => 'File too large. Maximum size is 100MB, your file is ' . round($fileSize/1024/1024, 2) . 'MB']);
    exit;
}

// Check temp file exists
if (!file_exists($fileTmp)) {
    writeLog("AJAX Upload failed for '{$fileName}': Temp file not found at '{$fileTmp}'");
    echo json_encode(['success' => false, 'error' => 'Temp file not found']);
    exit;
}

// Generate unique filename
$newFileName = uniqid('video_') . '_' . time() . '.' . $fileExt;
$targetPath = $uploadDir . DIRECTORY_SEPARATOR . $newFileName;

writeLog("AJAX Upload: Moving to {$targetPath}", 'INFO');

// Move uploaded file
if (move_uploaded_file($fileTmp, $targetPath)) {
    // Set file permissions on Windows (Everyone Full Control)
    setWindowsPermissions($targetPath);
    
    // Verify file exists
    if (file_exists($targetPath)) {
        writeLog("AJAX Upload successful: '{$fileName}' -> '{$newFileName}'", 'SUCCESS');
        echo json_encode([
            'success' => true,
            'filename' => $newFileName,
            'original_name' => $fileName,
            'size' => $fileSize,
            'path' => 'assets/uploads/videos/' . $newFileName
        ]);
    } else {
        writeLog("AJAX Upload failed for '{$fileName}': File moved but not found at destination");
        echo json_encode(['success' => false, 'error' => 'File moved but not found at destination']);
    }
} else {
    $error = error_get_last();
    writeLog("AJAX Upload failed for '{$fileName}': Failed to move file - " . ($error['message'] ?? 'Unknown error') . " (From: {$fileTmp}, To: {$targetPath})");
    echo json_encode(['success' => false, 'error' => 'Failed to save uploaded file: ' . ($error['message'] ?? 'Unknown error')]);
}
