<?php
/**
 * Database Helper - Unified data storage for localhost and cPanel
 * Handles JSON file reading/writing with proper error handling
 */

class DatabaseHelper {
    
    /**
     * Get the data directory - works on both localhost and cPanel
     */
    public static function getDataDir() {
        return __DIR__ . '/../data';
    }
    
    /**
     * Get absolute file path for data files
     */
    public static function getFilePath($filename) {
        $dataDir = self::getDataDir();
        if (!is_dir($dataDir)) {
            mkdir($dataDir, 0755, true);
        }
        return $dataDir . '/' . basename($filename);
    }
    
    /**
     * Load JSON file safely
     */
    public static function loadJson($filename, $default = []) {
        $filePath = self::getFilePath($filename);
        
        if (!file_exists($filePath)) {
            return $default;
        }
        
        $content = file_get_contents($filePath);
        if ($content === false) {
            error_log("Failed to read file: $filePath");
            return $default;
        }
        
        $decoded = json_decode($content, true);
        if ($decoded === null && $content !== '[]' && $content !== '{}') {
            error_log("JSON decode error in $filePath: " . json_last_error_msg());
            return $default;
        }
        
        return $decoded ?? $default;
    }
    
    /**
     * Save JSON file safely with proper error handling and backups
     */
    public static function saveJson($filename, $data) {
        $filePath = self::getFilePath($filename);
        $dataDir = self::getDataDir();
        
        // Ensure directory exists
        if (!is_dir($dataDir)) {
            if (!mkdir($dataDir, 0755, true)) {
                error_log("Failed to create data directory: $dataDir");
                return false;
            }
        }
        
        // Create backup of existing file
        if (file_exists($filePath)) {
            $backupDir = $dataDir . '/.backups';
            if (!is_dir($backupDir)) {
                mkdir($backupDir, 0755, true);
            }
            $backupFile = $backupDir . '/' . basename($filePath) . '.backup.' . time();
            if (!copy($filePath, $backupFile)) {
                error_log("Failed to create backup: $backupFile");
            }
        }
        
        // Encode data
        $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        if ($json === false) {
            error_log("JSON encode error: " . json_last_error_msg());
            return false;
        }
        
        // Write to temporary file first
        $tempFile = $filePath . '.tmp';
        if (file_put_contents($tempFile, $json, LOCK_EX) === false) {
            error_log("Failed to write to temporary file: $tempFile");
            return false;
        }
        
        // Atomic rename
        if (!rename($tempFile, $filePath)) {
            error_log("Failed to rename temporary file: $tempFile to $filePath");
            @unlink($tempFile);
            return false;
        }
        
        // Clear any opcache if available
        if (function_exists('opcache_invalidate')) {
            opcache_invalidate($filePath, true);
        }
        
        return true;
    }
    
    /**
     * Append to JSON array safely
     */
    public static function appendJson($filename, $item) {
        $data = self::loadJson($filename, []);
        
        // Ensure it's an array
        if (!is_array($data)) {
            $data = [];
        }
        
        $data[] = $item;
        
        return self::saveJson($filename, $data);
    }
    
    /**
     * Get uploads directory
     */
    public static function getUploadsDir() {
        $uploadsDir = __DIR__ . '/../uploads';
        if (!is_dir($uploadsDir)) {
            mkdir($uploadsDir, 0755, true);
        }
        return $uploadsDir;
    }
    
    /**
     * Save uploaded file
     */
    public static function saveUploadedFile($uploadedFile) {
        if (!isset($uploadedFile['tmp_name']) || !isset($uploadedFile['name'])) {
            return ['success' => false, 'error' => 'Invalid file upload'];
        }
        
        $uploadsDir = self::getUploadsDir();
        $filename = basename($uploadedFile['name']);
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        // Allowed extensions
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'webm', 'mov', 'avi', 'mkv'];
        if (!in_array($ext, $allowed)) {
            return ['success' => false, 'error' => 'File type not allowed'];
        }
        
        // Generate unique filename
        $newFilename = 'upload_' . time() . '_' . uniqid() . '.' . $ext;
        $destination = $uploadsDir . '/' . $newFilename;
        
        if (!move_uploaded_file($uploadedFile['tmp_name'], $destination)) {
            return ['success' => false, 'error' => 'Failed to move uploaded file'];
        }
        
        return ['success' => true, 'filename' => 'uploads/' . $newFilename, 'path' => $destination];
    }
}
?>
