<?php
include 'config.php';

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

// Auth check
$auth_token = $_REQUEST['auth_token'] ?? '';
if ($auth_token !== AUTH_TOKEN) {
    die(json_encode(["error" => "❌ Unauthorized Access"]));
}

// Folder mapper
function getFolder($type) {
    return match ($type) {
        'anugaman' => ANUGAMAN_DIR,
        'mudda' => MUDDA_DIR,
        'db' => DB_DIR,
        'labour' => LABOURDETAILS,
        'admin' => APP_DIR_ADMIN,
        default => APP_DIR, // fallback
    };
}

// Get latest file from a folder
function getLatestFile($folder) {
    if (!is_dir($folder)) return null;
    $files = array_diff(scandir($folder, SCANDIR_SORT_DESCENDING), ['.', '..']);
    return reset($files) ?: null;
}

$action = $_REQUEST['action'] ?? '';

switch ($action) {

    case 'check_version':
        $versions = [
            "db" => getLatestFile(DB_DIR),
            "labour" => getLatestFile(LABOURDETAILS),
            "adminapp" => getLatestFile(APP_DIR_ADMIN),
            "app" => getLatestFile(APP_DIR)
        ];
        echo json_encode($versions);
        break;

        case 'download':
        $filename = $_GET['filename'] ?? '';
        $type = $_GET['type'] ?? '';
        $folder = getFolder($type);
        $file_path = $folder . $filename;

        if (file_exists($file_path)) {
            $filesize = filesize($file_path);

            header("Content-Type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"$filename\"");
            header("Content-Length: $filesize");

            flush();
            readfile($file_path);
            exit;
        } else {
            echo json_encode(["error" => "❌ File not found"]);
        }
        break;
    case 'upload':
        $type = $_POST['type'] ?? '';
        $folder = getFolder($type);

        if (!is_dir($folder)) mkdir($folder, 0777, true);

        if (isset($_FILES['file'])) {
            $filename = basename($_FILES["file"]["name"]);
            $target_file = $folder . $filename;

            if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
                echo json_encode(["success" => true, "message" => "✅ '{$type}' फोल्डरमा फाइल अपलोड सफल", "filename" => $filename]);
            } else {
                echo json_encode(["success" => false, "message" => "❌ '{$type}' फोल्डरमा फाइल अपलोड असफल"]);
            }
        } else {
            echo json_encode(["success" => false, "message" => "❌ 'file' field खाली छ"]);
        }
        break;
        case 'list':
        $type = $_GET['type'] ?? '';
        $folder = getFolder($type);
        if (!is_dir($folder)) {
            echo json_encode([]);
            break;
        }
        $files = array_diff(scandir($folder), ['.', '..']);
echo json_encode($files);
        break;
        
        case 'delete':
        $type = $_POST['type'] ?? '';
        $filename = $_POST['filename'] ?? '';

        if (!$type || !$filename) {
            echo json_encode(["success" => false, "message" => "❌ 'type' वा 'filename' खाली छ"]);
            break;
        }

        $folder = getFolder($type);
        $file_path = $folder . $filename;

        if (file_exists($file_path)) {
            if (unlink($file_path)) {
                echo json_encode(["success" => true, "message" => "✅ फाइल सफलतापूर्वक हटाइयो"]);
            } else {
                echo json_encode(["success" => false, "message" => "❌ फाइल हटाउन असफल"]);
            }
        } else {
            echo json_encode(["success" => false, "message" => "❌ फाइल फेला परेन"]);
        }
        break;

    default:
        echo json_encode(["error" => "❌ Invalid action"]);
        break;
}