<?php
// manager/users/api.php

// ===== CONFIG =====
$CONTENT_ROOT = __DIR__; // /manager/users
$API_KEY = 'REPLACE_ME_WITH_A_SECRET_KEY'; // <<< set same key in your Python code
$ALLOWED_DAYS = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

// ===== Helpers =====
function respond($ok, $data=[], $http=200) {
    http_response_code($http);
    header('Content-Type: application/json');
    echo json_encode(['ok'=>$ok] + $data);
    exit;
}

// Auth
$headers = getallheaders();
if (!isset($headers['X-API-Key']) || $headers['X-API-Key'] !== $API_KEY) {
    respond(false, ['error'=>'Unauthorized'], 401);
}

// CORS (optional, useful while testing)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-API-Key, Content-Type');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

// ===== Actions =====
$action = $_GET['action'] ?? $_POST['action'] ?? '';

function safe_join($base, $parts) {
    $p = $base;
    foreach ($parts as $part) {
        $part = trim($part, "/\\.");
        $p = $p . DIRECTORY_SEPARATOR . $part;
    }
    $real = realpath($p) ?: $p; // for not-yet-existing paths during checks we keep $p
    // prevent path traversal
    $baseReal = realpath($base);
    if ($baseReal && strpos(realpath(dirname($real)) ?: $real, $baseReal) !== 0) {
        respond(false, ['error'=>'Invalid path.']);
    }
    return $p;
}

// GET /api.php?action=validate&account=...&week=...
if ($action === 'validate') {
    $account = $_GET['account'] ?? '';
    $week    = $_GET['week'] ?? '';
    if (!$account) respond(false, ['error'=>'Missing account']);
    if (!$week)    respond(false, ['error'=>'Missing week']);

    $accountDir = safe_join($CONTENT_ROOT, [$account]);
    if (!is_dir($accountDir)) {
        respond(false, ['error'=>"Account '$account' does not exist on server"]);
    }

    $weekDir = safe_join($accountDir, [$week]);
    if (!is_dir($weekDir)) {
        respond(false, ['error'=>"Week '$week' not found under account '$account'"]);
    }

    // Determine projects: immediate subfolders. If none, project is "__root__".
    $projects = array_values(array_filter(scandir($weekDir), function($d) use ($weekDir) {
        return $d !== '.' && $d !== '..' && is_dir($weekDir . DIRECTORY_SEPARATOR . $d);
    }));

    $result = [];
    if (count($projects) === 0) {
        // Days directly under week
        $days = array_values(array_filter(scandir($weekDir), function($d) use ($weekDir) {
            return $d !== '.' && $d !== '..' && is_dir($weekDir . DIRECTORY_SEPARATOR . $d);
        }));
        $result['__root__'] = $days;
    } else {
        foreach ($projects as $proj) {
            $projDir = $weekDir . DIRECTORY_SEPARATOR . $proj;
            $days = array_values(array_filter(scandir($projDir), function($d) use ($projDir) {
                return $d !== '.' && $d !== '..' && is_dir($projDir . DIRECTORY_SEPARATOR . $d);
            }));
            $result[$proj] = $days;
        }
    }

    respond(true, ['projects'=>$result]);
}

// POST /api.php?action=upload
// form-data: account, week, project, day, file (captions_log.txt content)
if ($action === 'upload') {
    $account = $_POST['account'] ?? '';
    $week    = $_POST['week'] ?? '';
    $project = $_POST['project'] ?? '';
    $day     = $_POST['day'] ?? '';
    if (!$account || !$week || !$day) respond(false, ['error'=>'Missing params (account/week/day)']);
    if (!$project) $project = '__root__';

    if (!in_array($day, $ALLOWED_DAYS, true)) {
        respond(false, ['error'=>"Invalid day '$day'"]);
    }

    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        respond(false, ['error'=>'Missing file upload']);
    }

    $accountDir = safe_join($CONTENT_ROOT, [$account]);
    if (!is_dir($accountDir)) {
        respond(false, ['error'=>"Account '$account' does not exist"]);
    }
    $weekDir = safe_join($accountDir, [$week]);
    if (!is_dir($weekDir)) {
        respond(false, ['error'=>"Week '$week' does not exist under '$account'"]);
    }

    $targetDir = ($project === '__root__') ? $weekDir : safe_join($weekDir, [$project]);
    if (!is_dir($targetDir)) {
        respond(false, ['error'=>"Project '$project' does not exist under week '$week'"]);
    }

    $dayDir = safe_join($targetDir, [$day]);
    if (!is_dir($dayDir)) {
        respond(false, ['error'=>"Day '$day' does not exist under project '$project'"]);
    }

$dest = $dayDir . DIRECTORY_SEPARATOR . 'captions_log.txt';
$tmp  = $_FILES['file']['tmp_name'];

// 🚨 NEW: refuse overwrite if file already exists
if (file_exists($dest)) {
    respond(false, ['error'=>"File already exists at '$dest'. Upload aborted."]);
}

// Save new file
if (!move_uploaded_file($tmp, $dest)) {
    // fallback: copy
    if (!copy($tmp, $dest)) {
        respond(false, ['error'=>"Failed to write file to '$dest'"]);
    }
}
@chmod($dest, 0644);

respond(true, ['message'=>'Uploaded']);

}

respond(false, ['error'=>'Unknown action']);
