<?php
header("Content-Type: application/json");

$DATA_FILE = __DIR__ . "/stored.txt";
$USERS_DIR = __DIR__ . "/users";

$action = $_GET['action'] ?? ''; // <-- MOVE HERE

// ---------- Helpers ----------
function deleteFolder($dir) {
    if (!file_exists($dir)) return;
    if (!is_dir($dir)) { @unlink($dir); return; }
    $files = array_diff(@scandir($dir) ?: [], ['.', '..']);
    foreach ($files as $file) {
        $path = "$dir/$file";
        if (is_dir($path)) { deleteFolder($path); }
        else { @unlink($path); }
    }
    @rmdir($dir);
}

function ensureFolder($path) {
    if (!file_exists($path)) { @mkdir($path, 0777, true); }
}


if ($action === "renameAccountFolder") {
    $input = json_decode(file_get_contents("php://input"), true);
    $user = $input["user"] ?? "";
    $oldAccount = $input["oldAccountName"] ?? "";
    $newAccount = $input["newAccountName"] ?? "";

    if (!$user || !$oldAccount || !$newAccount) {
        echo json_encode(["success" => false, "error" => "Missing required data"]);
        exit;
    }

    $baseDir = __DIR__ . "/users/$user";
    if (!is_dir($baseDir)) {
        echo json_encode(["success" => false, "error" => "User folder not found"]);
        exit;
    }

    // Find all week folders under this user
    $weekFolders = glob("$baseDir/week-*", GLOB_ONLYDIR);

    foreach ($weekFolders as $weekFolder) {
        $oldPath = "$weekFolder/$oldAccount";
        $newPath = "$weekFolder/$newAccount";

        if (is_dir($oldPath)) {
            // ✅ Rename the folder
            if (!rename($oldPath, $newPath)) {
                echo json_encode(["success" => false, "error" => "Failed to rename $oldPath"]);
                exit;
            }
        }
    }

    echo json_encode(["success" => true, "message" => "Account folders renamed successfully"]);
    exit;
}

if ($action === "getSessionStatus") {
    $file = __DIR__ . "/sess.txt";
    if (file_exists($file)) {
        $content = file_get_contents($file);
        $data = json_decode($content, true);

        if (is_array($data) && isset($data['status'])) {
            echo json_encode($data);
        } else {
            echo json_encode(["status" => "unknown", "timestamp" => null]);
        }
    } else {
        echo json_encode(["status" => "unknown", "timestamp" => null]);
    }
    exit;
}


if ($action === "saveSessionStatus") {
    $input = json_decode(file_get_contents("php://input"), true);
    $status = $input["status"] ?? "unknown";
    $timestamp = $input["timestamp"] ?? date("c");

    $log = [
        "status" => $status,
        "timestamp" => $timestamp
    ];

    file_put_contents(__DIR__ . "/sess.txt", json_encode($log, JSON_PRETTY_PRINT));

    echo json_encode(["success" => true, "message" => "Session status saved"]);
    exit;
}


function loadData($file) {
    if (!file_exists($file)) {
        file_put_contents($file, json_encode(["users" => [], "results" => []], JSON_PRETTY_PRINT));
    }

    $json = file_get_contents($file);
    $data = json_decode($json, true);
    if (!is_array($data)) $data = [];

    if (!isset($data["users"]) || !is_array($data["users"])) $data["users"] = [];
    if (!isset($data["results"]) || !is_array($data["results"])) $data["results"] = [];

    // ✅ Normalize: ensure every account has a boolean `banned`
    foreach ($data["users"] as &$user) {
        if (!isset($user["accounts"]) || !is_array($user["accounts"])) continue;
        foreach ($user["accounts"] as &$acc) {
            $acc["banned"] = isset($acc["banned"]) ? (bool)$acc["banned"] : false;
        }
    }
    unset($user, $acc);

    return $data;
}


function saveData($file, $data) {
    $out = [
        "users"   => [],
        "results" => isset($data["results"]) ? $data["results"] : []
    ];

    if (isset($data["users"]) && is_array($data["users"])) {
        foreach ($data["users"] as $user) {
            $newUser = $user;
            if (isset($newUser["accounts"]) && is_array($newUser["accounts"])) {
                foreach ($newUser["accounts"] as &$acc) {
                    // ✅ Preserve banned if already set
                    if (!isset($acc["banned"])) {
                        $acc["banned"] = false;
                    } else {
                        $acc["banned"] = (bool)$acc["banned"];
                    }
                }
            }
            $out["users"][] = $newUser;
        }
    }

    file_put_contents($file, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function is_list_array($arr) {
    if (!is_array($arr)) return false;
    return array_keys($arr) === range(0, count($arr)-1);
}



if ($action === 'load') {
    echo json_encode(loadData($DATA_FILE));
    exit;
}

if ($action === 'save') {
    $raw  = file_get_contents("php://input");
    $data = json_decode($raw, true);
    if (!$data || !isset($data['users']) || !is_array($data['users'])) {
        echo json_encode(["error" => "Invalid data"]);
        exit;
    }

    $oldData = loadData($DATA_FILE);

    // If old stored.txt was corrupted (results written into 'users'), migrate it
    if (!is_list_array($oldData['users'])) {
        // Treat oldData['users'] as results map and reset users list
        $oldData = [
            "users"   => [],                 // there is no reliable array anymore, start fresh
            "results" => $oldData['users']   // migrate old map into results
        ];
        saveData($DATA_FILE, $oldData);
    }

    // Build lookup of new users/accounts
    $newUsers = $data['users'];
    $newUsersByName = [];
    foreach ($newUsers as $u) {
        if (!isset($u['name'])) continue;
        $newUsersByName[$u['name']] = $u;
    }

    // Delete users/accounts that no longer exist
    foreach ($oldData['users'] as $oldUser) {
        if (!isset($oldUser['name'])) continue; // safety
        $uname = $oldUser['name'];

if (!isset($newUsersByName[$uname])) {
    // delete whole user folder
    $userPath = $USERS_DIR . "/" . $uname;
    if ($uname !== '' && basename($userPath) !== 'users') {
        deleteFolder($userPath);
    }

    // ✅ Delete user's results from stored.txt
    if (isset($oldData['results'][$uname])) {
        unset($oldData['results'][$uname]);
    }

    continue;
}


        // user still exists -> check accounts
        $newUser = $newUsersByName[$uname];
        $oldAccounts = isset($oldUser['accounts']) && is_array($oldUser['accounts']) ? $oldUser['accounts'] : [];
        $newAccounts = isset($newUser['accounts']) && is_array($newUser['accounts']) ? $newUser['accounts'] : [];

        $newAccNames = [];
        foreach ($newAccounts as $na) {
            if (isset($na['name'])) $newAccNames[$na['name']] = true;
        }

foreach ($oldAccounts as $oa) {
    if (!isset($oa['name'])) continue;
    $accountName = $oa['name'];

    // If account no longer exists in the new data
    if (!isset($newAccNames[$accountName])) {
        // 1. Delete its folder
// ✅ NEW
if ($uname !== '' && $accountName !== '') {
    $userFolder = $USERS_DIR . "/" . $uname;

    if (is_dir($userFolder)) {
        // Loop through all week folders
        $weeks = array_diff(scandir($userFolder), ['.', '..']);
        foreach ($weeks as $weekFolder) {
            $accountPath = "$userFolder/$weekFolder/$accountName";
            if (is_dir($accountPath)) {
                deleteFolder($accountPath);
            }
        }
    }
}
        // 2. Delete related results in stored.txt
        if (isset($oldData['results'][$uname][$accountName])) {
            unset($oldData['results'][$uname][$accountName]);

            // If this user has no more accounts in results, clean up that user too
            if (empty($oldData['results'][$uname])) {
                unset($oldData['results'][$uname]);
            }
        }
    }
}

    }

    // Persist: keep results from oldData
// ✅ Merge new results with existing ones
$newResults = isset($data['results']) ? $data['results'] : [];
$mergedResults = array_replace_recursive($oldData['results'], $newResults);

// ✅ Merge users: preserve banned flags
$finalUsers = [];
foreach ($newUsers as $newUser) {
    if (!isset($newUser['accounts'])) {
        $finalUsers[] = $newUser;
        continue;
    }

    $mergedAccounts = [];
    foreach ($newUser['accounts'] as $acc) {
        $accName = $acc['name'];
        $accBanned = false;

        // Check old data for banned status
        foreach ($oldData['users'] as $oldUser) {
            if ($oldUser['name'] === $newUser['name']) {
                foreach ($oldUser['accounts'] as $oldAcc) {
                    if ($oldAcc['name'] === $accName && isset($oldAcc['banned'])) {
                        $accBanned = $oldAcc['banned'];
                    }
                }
            }
        }

        // Preserve banned status
        $acc['banned'] = $accBanned;
        $mergedAccounts[] = $acc;
    }

    $newUser['accounts'] = $mergedAccounts;
    $finalUsers[] = $newUser;
}

$out = [
    "users"   => $finalUsers,
    "results" => $mergedResults
];

saveData($DATA_FILE, $out);



// Ensure folders for all users/accounts/days
foreach ($newUsers as $user) {
    if (!isset($user['name'])) continue;
    $userFolder = $USERS_DIR . "/" . $user['name'];
    ensureFolder($userFolder);

    // Use selectedMonday to determine the current week
    $currentMonday = date('Y-m-d', strtotime('monday this week'));
    $weekFolderName = "week-" . strtolower(date('M-d', strtotime($currentMonday)));

    $weekFolderPath = $userFolder . "/" . $weekFolderName;
    ensureFolder($weekFolderPath);

    $accounts = isset($user['accounts']) ? $user['accounts'] : [];
    foreach ($accounts as $account) {
        if (!isset($account['name'])) continue;

        // ✅ FIX: Put account inside the week folder
        $accountFolder = $weekFolderPath . "/" . $account['name'];
        ensureFolder($accountFolder);

        $days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
        foreach ($days as $day) {
            ensureFolder($accountFolder . "/" . $day);
        }
    }
}


    echo json_encode(["message" => "Data saved successfully!"]);
    exit;
}

if ($_GET['action'] === 'createWeekFolder') {
    $data = json_decode(file_get_contents("php://input"), true);
    $user = preg_replace('/[^a-zA-Z0-9_-]/', '', $data['user']);
    $weekFolder = preg_replace('/[^a-zA-Z0-9_-]/', '', $data['weekFolder']);

    $basePath = __DIR__ . "/users/$user/$weekFolder";

    if (!is_dir($basePath)) {
        mkdir($basePath, 0777, true); // recursive creation
    }

    echo json_encode(["status" => "success", "folder" => "$basePath"]);
    exit;
}

if ($_GET['action'] === 'verifyWeekFolder') {
    $data = json_decode(file_get_contents("php://input"), true);

    $user = preg_replace('/[^a-zA-Z0-9_-]/', '', $data['user']);
    $weekFolder = preg_replace('/[^a-zA-Z0-9_-]/', '', $data['weekFolder']);
    $account = preg_replace('/[^a-zA-Z0-9_-]/', '', $data['account']);
    $day = preg_replace('/[^a-zA-Z0-9_-]/', '', $data['day']);

    $basePath = __DIR__ . "/users/$user/$weekFolder/$account/$day";

    if (!is_dir($basePath)) {
        // Create recursively if missing
        mkdir($basePath, 0777, true);

        echo json_encode([
            "status" => "missing",
            "message" => "Folder structure was missing and has now been created.",
            "createdPath" => $basePath
        ]);
        exit;
    }

    echo json_encode([
        "status" => "exists",
        "message" => "Folder already exists.",
        "path" => $basePath
    ]);
    exit;
}


if ($_GET['action'] === 'update_banned') {
    $input = json_decode(file_get_contents("php://input"), true);
    $accountName = $input['accountName'] ?? null;
    $banned = $input['banned'] ?? false;

    $stored = json_decode(file_get_contents("stored.txt"), true);
    foreach ($stored['users'] as &$user) {
        foreach ($user['accounts'] as &$acc) {
            if ($acc['name'] === $accountName) {
                $acc['banned'] = $banned;
            }
        }
    }
    file_put_contents("stored.txt", json_encode($stored, JSON_PRETTY_PRINT));
    echo json_encode(["status"=>"ok", "account"=>$accountName, "banned"=>$banned]);
    exit;
}


if ($action === 'checkAndCreateFolders') {
    $input = json_decode(file_get_contents('php://input'), true);
    $user = preg_replace('/[^a-zA-Z0-9_-]/', '', $input['user']);
    $weekFolder = preg_replace('/[^a-zA-Z0-9_-]/', '', $input['weekFolder']);
    $account = preg_replace('/[^a-zA-Z0-9_-]/', '', $input['account']);
    $day = preg_replace('/[^a-zA-Z0-9_-]/', '', $input['day']);

    if (!$user || !$weekFolder || !$account || !$day) {
        echo json_encode(["success" => false, "error" => "Invalid input"]);
        exit;
    }

    $baseDir = __DIR__ . "/users/$user/$weekFolder/$account";

    // Create week folder if missing
    if (!file_exists(dirname($baseDir))) {
        mkdir(dirname($baseDir), 0777, true);
    }

    // Create account folder
    if (!file_exists($baseDir)) {
        mkdir($baseDir, 0777, true);
    }

    // Create day folders
    $days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
    foreach ($days as $d) {
        $dayPath = "$baseDir/$d";
        if (!file_exists($dayPath)) {
            mkdir($dayPath, 0777, true);
        }
    }

    echo json_encode(["success" => true, "message" => "Folders verified/created"]);
    exit;
}


if ($_GET['action'] === 'saveResult') {
    $input = json_decode(file_get_contents('php://input'), true);

    $file = 'stored.txt';
    $data = file_exists($file) ? json_decode(file_get_contents($file), true) : [];

    $user = $input['user'];
    $account = $input['account'];
    $week = $input['week'];
    $day = $input['day'];
    $result = $input['result'];
    $date = $input['date']; // <-- New date field

    if (!isset($data['results'][$user])) $data['results'][$user] = [];
    if (!isset($data['results'][$user][$account])) $data['results'][$user][$account] = [];
    if (!isset($data['results'][$user][$account][$week])) $data['results'][$user][$account][$week] = [];

    // ✅ Save result with both text and actual date
    $data['results'][$user][$account][$week][$day] = [
        "result" => $result,
        "date" => $date
    ];

    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
    echo json_encode(["success" => true]);
    exit;
}

if ($action === "renameUserFolder") {
    $input = json_decode(file_get_contents("php://input"), true);
    $oldUser = $input["oldUserName"] ?? "";
    $newUser = $input["newUserName"] ?? "";

    if (!$oldUser || !$newUser) {
        echo json_encode(["success" => false, "error" => "Missing data"]);
        exit;
    }

    $oldPath = __DIR__ . "/users/$oldUser";
    $newPath = __DIR__ . "/users/$newUser";

    if (!is_dir($oldPath)) {
        echo json_encode(["success" => false, "error" => "Old user folder not found"]);
        exit;
    }

    if (is_dir($newPath)) {
        echo json_encode(["success" => false, "error" => "A folder with the new name already exists"]);
        exit;
    }

    if (!rename($oldPath, $newPath)) {
        echo json_encode(["success" => false, "error" => "Failed to rename user folder"]);
        exit;
    }

    echo json_encode(["success" => true, "message" => "User folder renamed successfully"]);
    exit;
}

if ($action === "insertEmptyCaptions") {
    $input = json_decode(file_get_contents("php://input"), true);
    $user = $input['user'];
    $account = $input['account'];
    $weekFolder = $input['weekFolder'];

    $basePath = __DIR__ . "/users/$user/$weekFolder/$account";
    $days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
    $content = "uidneuwueifneuifnewfwuinfw";

    try {
        foreach ($days as $day) {
            $dayPath = "$basePath/$day";
            if (!is_dir($dayPath)) {
                mkdir($dayPath, 0777, true);
            }
            file_put_contents("$dayPath/captions_log.txt", $content);
        }
        echo json_encode(["success" => true]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "error" => $e->getMessage()]);
    }
    exit;
}


echo json_encode(["error" => "Invalid action"]);
