<?php
/**
 * Common Functions
 * Video Portal Management System
 */

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    // Fix session path for IIS/Windows
    $sessionPath = ini_get('session.save_path');
    if (empty($sessionPath) || !is_writable($sessionPath)) {
        $sessionPath = __DIR__ . '/../tmp/sessions';
        if (!file_exists($sessionPath)) {
            @mkdir($sessionPath, 0755, true);
        }
        ini_set('session.save_path', $sessionPath);
    }
    session_start();
}

/**
 * Get setting value from database
 */
function getSetting($key, $default = '') {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        return $result ? $result['setting_value'] : $default;
    } catch (PDOException $e) {
        return $default;
    }
}

/**
 * Update setting value
 */
function updateSetting($key, $value) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
        return $stmt->execute([$value, $key]);
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Get all settings as array
 */
function getAllSettings() {
    global $pdo;
    $settings = [];
    try {
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
        while ($row = $stmt->fetch()) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
    } catch (PDOException $e) {
        // Return empty array on error
    }
    return $settings;
}

/**
 * Check if user is logged in
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Check if user is admin
 */
function isAdmin() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
}

/**
 * Redirect to URL
 */
function redirect($url) {
    header("Location: $url");
    exit;
}

/**
 * Sanitize input
 */
function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Generate CSRF token
 */
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Verify CSRF token
 */
function verifyCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Get user by ID
 */
function getUserById($id) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * Get all categories
 */
function getCategories($activeOnly = true) {
    global $pdo;
    try {
        $sql = "SELECT * FROM categories";
        if ($activeOnly) {
            $sql .= " WHERE status = 'active'";
        }
        $sql .= " ORDER BY sort_order ASC";
        $stmt = $pdo->query($sql);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Get videos with filters
 */
function getVideos($categoryId = null, $status = 'active', $limit = null) {
    global $pdo;
    try {
        $sql = "SELECT v.*, c.name as category_name, u.username as created_by_name 
                FROM videos v 
                LEFT JOIN categories c ON v.category_id = c.id 
                LEFT JOIN users u ON v.created_by = u.id 
                WHERE 1=1";
        $params = [];
        
        if ($status) {
            $sql .= " AND v.status = ?";
            $params[] = $status;
        }
        
        if ($categoryId) {
            $sql .= " AND v.category_id = ?";
            $params[] = $categoryId;
        }
        
        $sql .= " ORDER BY v.created_at DESC";
        
        if ($limit) {
            $sql .= " LIMIT " . intval($limit);
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Get video by ID
 */
function getVideoById($id) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT v.*, c.name as category_name 
                               FROM videos v 
                               LEFT JOIN categories c ON v.category_id = c.id 
                               WHERE v.id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * Log download
 */
function logDownload($videoId, $userId) {
    global $pdo;
    try {
        // Insert log
        $stmt = $pdo->prepare("INSERT INTO download_logs (video_id, user_id, ip_address) VALUES (?, ?, ?)");
        $stmt->execute([$videoId, $userId, $_SERVER['REMOTE_ADDR'] ?? '']);
        
        // Update download count
        $stmt = $pdo->prepare("UPDATE videos SET download_count = download_count + 1 WHERE id = ?");
        $stmt->execute([$videoId]);
        
        return true;
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Handle file upload
 */
function uploadFile($file, $targetDir, $allowedTypes = ['jpg', 'jpeg', 'png', 'gif']) {
    $fileName = $file['name'] ?? 'unknown';
    
    // Check for upload errors
    if (!isset($file['error'])) {
        writeLog("Upload failed for '{$fileName}': No file data received");
        return ['success' => false, 'error' => 'No file uploaded'];
    }
    
    // Handle specific upload errors
    switch ($file['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            $maxSize = ini_get('upload_max_filesize');
            writeLog("Upload failed for '{$fileName}': File too large (server limit: {$maxSize})");
            return ['success' => false, 'error' => 'File too large (server limit: ' . $maxSize . ')'];
        case UPLOAD_ERR_PARTIAL:
            writeLog("Upload failed for '{$fileName}': File only partially uploaded");
            return ['success' => false, 'error' => 'File only partially uploaded'];
        case UPLOAD_ERR_NO_FILE:
            writeLog("Upload failed: No file was uploaded");
            return ['success' => false, 'error' => 'No file was uploaded'];
        case UPLOAD_ERR_NO_TMP_DIR:
            $tmpDir = ini_get('upload_tmp_dir') ?: sys_get_temp_dir();
            writeLog("Upload failed for '{$fileName}': Missing temp folder (configured: {$tmpDir})");
            return ['success' => false, 'error' => 'Missing temp folder'];
        case UPLOAD_ERR_CANT_WRITE:
            writeLog("Upload failed for '{$fileName}': Failed to write file to disk - check disk permissions");
            return ['success' => false, 'error' => 'Failed to write file to disk'];
        case UPLOAD_ERR_EXTENSION:
            writeLog("Upload failed for '{$fileName}': PHP extension stopped the upload");
            return ['success' => false, 'error' => 'Upload blocked by PHP extension'];
        default:
            writeLog("Upload failed for '{$fileName}': Unknown error code: " . $file['error']);
            return ['success' => false, 'error' => 'Unknown upload error (code: ' . $file['error'] . ')'];
    }
    
    $fileName = $file['name'];
    $fileSize = $file['size'];
    $fileTmp = $file['tmp_name'];
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    writeLog("Processing upload: '{$fileName}' (Size: " . round($fileSize/1024/1024, 2) . "MB, Type: {$fileExt})", 'INFO');
    
    if (!in_array($fileExt, $allowedTypes)) {
        writeLog("Upload failed for '{$fileName}': Invalid file type '{$fileExt}'. Allowed: " . implode(', ', $allowedTypes));
        return ['success' => false, 'error' => 'Invalid file type: ' . $fileExt];
    }
    
    // Max file size 100MB
    if ($fileSize > 100 * 1024 * 1024) {
        writeLog("Upload failed for '{$fileName}': File too large (" . round($fileSize/1024/1024, 2) . "MB > 100MB)");
        return ['success' => false, 'error' => 'File too large (max 100MB)'];
    }
    
    // Check if temp file exists
    if (!file_exists($fileTmp)) {
        writeLog("Upload failed for '{$fileName}': Temp file not found at '{$fileTmp}'");
        return ['success' => false, 'error' => 'Temp file not found'];
    }
    
    // Create directory if not exists
    if (!file_exists($targetDir)) {
        writeLog("Creating upload directory: {$targetDir}", 'INFO');
        if (!@mkdir($targetDir, 0755, true)) {
            $error = error_get_last();
            writeLog("Upload failed for '{$fileName}': Failed to create directory '{$targetDir}' - " . ($error['message'] ?? 'Unknown error'));
            return ['success' => false, 'error' => 'Failed to create upload directory'];
        }
        // Set directory permissions on Windows
        setWindowsPermissions($targetDir);
    }
    
    // Check if directory is writable
    if (!is_writable($targetDir)) {
        writeLog("Upload failed for '{$fileName}': Directory not writable '{$targetDir}'");
        return ['success' => false, 'error' => 'Upload directory is not writable'];
    }
    
    // Generate unique filename
    $newFileName = uniqid() . '_' . time() . '.' . $fileExt;
    $targetPath = rtrim($targetDir, '/\\') . DIRECTORY_SEPARATOR . $newFileName;
    
    writeLog("Moving file to: {$targetPath}", 'INFO');
    
    if (move_uploaded_file($fileTmp, $targetPath)) {
        // Set file permissions on Windows (Everyone Full Control)
        setWindowsPermissions($targetPath);
        
        // Verify file was created
        if (file_exists($targetPath)) {
            writeLog("Upload successful: '{$fileName}' -> '{$newFileName}'", 'SUCCESS');
            return ['success' => true, 'filename' => $newFileName, 'path' => $targetPath];
        } else {
            writeLog("Upload failed for '{$fileName}': File moved but not found at destination");
            return ['success' => false, 'error' => 'File moved but not found'];
        }
    }
    
    $error = error_get_last();
    writeLog("Upload failed for '{$fileName}': Failed to move file - " . ($error['message'] ?? 'Unknown error') . " (From: {$fileTmp}, To: {$targetPath})");
    return ['success' => false, 'error' => 'Failed to move uploaded file'];
}

/**
 * Set Windows permissions (Everyone Full Control) for IIS
 */
function setWindowsPermissions($path) {
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $path = str_replace('/', '\\', $path);
        @exec('icacls "' . $path . '" /grant Everyone:F /T /Q 2>&1', $output, $returnCode);
        if ($returnCode !== 0) {
            writeLog('Permission Error: Failed to set permissions on ' . $path . ' - ' . implode(', ', $output));
        }
        return $returnCode === 0;
    }
    return true;
}

/**
 * Write to log file
 */
function writeLog($message, $type = 'ERROR') {
    $logDir = __DIR__ . '/../logs';
    if (!file_exists($logDir)) {
        @mkdir($logDir, 0755, true);
        // Set permissions on Windows
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            @exec('icacls "' . str_replace('/', '\\', $logDir) . '" /grant Everyone:F /T /Q 2>&1');
        }
    }
    
    $logFile = $logDir . '/upload_' . date('Y-m-d') . '.log';
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[{$timestamp}] [{$type}] {$message}" . PHP_EOL;
    
    @file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
}

/**
 * Format date
 */
function formatDate($date, $format = 'd/m/Y H:i') {
    return date($format, strtotime($date));
}

/**
 * Get dashboard stats
 */
function getDashboardStats() {
    global $pdo;
    $stats = [];
    
    try {
        // Total users
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM users WHERE role = 'user'");
        $stats['total_users'] = $stmt->fetch()['count'];
        
        // Total videos
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM videos");
        $stats['total_videos'] = $stmt->fetch()['count'];
        
        // Total downloads
        $stmt = $pdo->query("SELECT SUM(download_count) as count FROM videos");
        $result = $stmt->fetch();
        $stats['total_downloads'] = $result['count'] ?? 0;
        
        // Total categories
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM categories");
        $stats['total_categories'] = $stmt->fetch()['count'];
        
    } catch (PDOException $e) {
        $stats = [
            'total_users' => 0,
            'total_videos' => 0,
            'total_downloads' => 0,
            'total_categories' => 0
        ];
    }
    
    return $stats;
}

/**
 * Get recent downloads
 */
function getRecentDownloads($limit = 10) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT dl.*, v.title as video_title, u.username 
                               FROM download_logs dl 
                               JOIN videos v ON dl.video_id = v.id 
                               JOIN users u ON dl.user_id = u.id 
                               ORDER BY dl.downloaded_at DESC 
                               LIMIT ?");
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        return [];
    }
}

/**
 * Flash message functions
 */
function setFlashMessage($type, $message) {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlashMessage() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}
