<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/lang.php";
require_once "../includes/csrf.php";

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
$canAdminModerate = ($roleId === 1 || $roleId === 5);
$isAgency = ($roleId === 3);
if (!$isAgency && !$canAdminModerate) {
    http_response_code(403);
    exit("Forbidden");
}
$csrf = csrfToken();

$requestId = (int)($_GET["request_id"] ?? 0);
$workerId = (int)($_GET["worker_id"] ?? 0);

$msg = "";
$err = "";

if ($isAgency) {
    $workersStmt = $pdo->prepare("
        SELECT w.id, w.first_name, w.last_name
        FROM workers w
        INNER JOIN worker_added_by wab ON wab.worker_id = w.id
        WHERE wab.added_by_user_id = ?
        ORDER BY w.id DESC
    ");
    $workersStmt->execute([(int)$user["id"]]);
} else {
    $workersStmt = $pdo->prepare("
        SELECT w.id, w.first_name, w.last_name
        FROM workers w
        ORDER BY w.id DESC
    ");
    $workersStmt->execute();
}
$agencyWorkers = $workersStmt->fetchAll(PDO::FETCH_ASSOC);

$docFields = [
    "consent_path" => "Consent",
    "passport_path" => "Passport",
    "diploma_path" => "Diploma",
    "invitation_letter_path" => "Invitation letter",
    "offer_letter_path" => "Offer letter"
];

function saveAgencyDoc(array $file, string $prefix): string {
    $maxSize = 8 * 1024 * 1024;
    $size = (int)($file["size"] ?? 0);
    if ($size <= 0 || $size > $maxSize) {
        throw new Exception("File must be up to 8MB.");
    }

    $name = (string)($file["name"] ?? "document.bin");
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $allowedExt = ["pdf", "jpg", "jpeg", "png", "doc", "docx"];
    if (!in_array($ext, $allowedExt, true)) {
        throw new Exception("Unsupported file type.");
    }

    $tmp = (string)($file["tmp_name"] ?? "");
    $mime = "";
    if (function_exists("finfo_open")) {
        $fi = finfo_open(FILEINFO_MIME_TYPE);
        if ($fi) {
            $mime = (string)finfo_file($fi, $tmp);
            finfo_close($fi);
        }
    }
    $allowedMime = [
        "application/pdf",
        "image/jpeg",
        "image/png",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/octet-stream"
    ];
    if ($mime !== "" && !in_array($mime, $allowedMime, true)) {
        throw new Exception("Unsupported MIME type.");
    }

    $uploadDir = __DIR__ . "/uploads/agency_docs";
    if (!is_dir($uploadDir) && !@mkdir($uploadDir, 0775, true)) {
        throw new Exception("Cannot create upload directory.");
    }

    $safeName = $prefix . "_" . date("YmdHis") . "_" . bin2hex(random_bytes(8)) . "." . $ext;
    $targetAbs = $uploadDir . "/" . $safeName;
    if (!move_uploaded_file($tmp, $targetAbs)) {
        throw new Exception("Unable to save uploaded file.");
    }

    return "uploads/agency_docs/" . $safeName;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!hash_equals($csrf, (string)($_POST["csrf"] ?? ""))) {
        $err = "Invalid CSRF token.";
    } else {
        $workerId = (int)($_POST["worker_id"] ?? 0);
        if ($workerId <= 0) {
            $err = "Please select a worker.";
        } else {
            $canUpload = false;
            if ($isAgency) {
                $ownsWorkerStmt = $pdo->prepare("
                    SELECT 1
                    FROM worker_added_by
                    WHERE worker_id = ? AND added_by_user_id = ?
                    LIMIT 1
                ");
                $ownsWorkerStmt->execute([$workerId, (int)$user["id"]]);
                $canUpload = (bool)$ownsWorkerStmt->fetchColumn();
            } else {
                $existsWorkerStmt = $pdo->prepare("SELECT 1 FROM workers WHERE id = ? LIMIT 1");
                $existsWorkerStmt->execute([$workerId]);
                $canUpload = (bool)$existsWorkerStmt->fetchColumn();
            }

            if (!$canUpload) {
                $err = "You can upload documents only for your workers.";
            } else {
                try {
                    $paths = [];
                    foreach ($docFields as $field => $label) {
                        if (!isset($_FILES[$field]) || !is_array($_FILES[$field])) continue;
                        $f = $_FILES[$field];
                        $fileErr = (int)($f["error"] ?? UPLOAD_ERR_NO_FILE);
                        if ($fileErr === UPLOAD_ERR_NO_FILE) continue;
                        if ($fileErr !== UPLOAD_ERR_OK) {
                            throw new Exception("Upload failed for " . $label . ".");
                        }
                        $paths[$field] = saveAgencyDoc($f, "wrk_" . $workerId . "_" . $field);
                    }

                    if (empty($paths)) {
                        throw new Exception("Please upload at least one document.");
                    }

                    $existingStmt = $pdo->prepare("
                        SELECT id FROM worker_documents
                        WHERE worker_id = ? AND agency_id = ?
                        LIMIT 1
                    ");
                    $existingStmt->execute([$workerId, (int)$user["id"]]);
                    $existingId = (int)$existingStmt->fetchColumn();

                    if ($existingId > 0) {
                        $setParts = [];
                        $params = [];
                        foreach ($paths as $col => $val) {
                            $setParts[] = "$col = ?";
                            $params[] = $val;
                        }
                        $params[] = $existingId;
                        $upd = $pdo->prepare("UPDATE worker_documents SET " . implode(", ", $setParts) . ", updated_at = NOW() WHERE id = ?");
                        $upd->execute($params);
                    } else {
                        $insertValues = [
                            $workerId,
                            (int)$user["id"],
                            $paths["consent_path"] ?? null,
                            $paths["passport_path"] ?? null,
                            $paths["diploma_path"] ?? null,
                            $paths["invitation_letter_path"] ?? null,
                            $paths["offer_letter_path"] ?? null
                        ];
                        $ins = $pdo->prepare("
                            INSERT INTO worker_documents
                            (worker_id, agency_id, consent_path, passport_path, diploma_path, invitation_letter_path, offer_letter_path)
                            VALUES (?, ?, ?, ?, ?, ?, ?)
                        ");
                        $ins->execute($insertValues);
                    }

                    $audit = $pdo->prepare("INSERT INTO audit_log (user_id, action) VALUES (?, ?)");
                    $audit->execute([(int)$user["id"], "agency_document_upload worker #{$workerId}"]);

                    $msg = "Documents uploaded successfully.";
                } catch (Throwable $e) {
                    $err = $e->getMessage();
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Agency Documentation - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/dashboard.css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width:760px;margin-top:30px;">
    <h3>Agency Documentation Upload</h3>
    <p>Request #<?= (int)$requestId ?> | Worker #<?= (int)$workerId ?></p>

    <?php if ($msg !== ""): ?>
        <div class="alert alert-success"><?= htmlspecialchars($msg, ENT_QUOTES, "UTF-8") ?></div>
    <?php endif; ?>
    <?php if ($err !== ""): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($err, ENT_QUOTES, "UTF-8") ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, "UTF-8") ?>">
        <div class="form-group">
            <label>Select existing worker</label>
            <select name="worker_id" class="form-control" required>
                <option value="">-- Select worker --</option>
                <?php foreach ($agencyWorkers as $aw): ?>
                    <?php
                        $wid = (int)($aw["id"] ?? 0);
                        $wname = trim((string)($aw["first_name"] ?? "") . " " . (string)($aw["last_name"] ?? ""));
                        if ($wname === "") $wname = "Worker #" . $wid;
                    ?>
                    <option value="<?= $wid ?>" <?= ($workerId === $wid ? "selected" : "") ?>><?= htmlspecialchars($wname, ENT_QUOTES, "UTF-8") ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Consent</label>
            <input type="file" name="consent_path" class="form-control">
            <small class="text-muted">Allowed: pdf, jpg, jpeg, png, doc, docx (max 8MB)</small>
        </div>
        <div class="form-group">
            <label>Passport</label>
            <input type="file" name="passport_path" class="form-control">
        </div>
        <div class="form-group">
            <label>Diploma</label>
            <input type="file" name="diploma_path" class="form-control">
        </div>
        <div class="form-group">
            <label>Invitation letter</label>
            <input type="file" name="invitation_letter_path" class="form-control">
        </div>
        <div class="form-group">
            <label>Offer letter</label>
            <input type="file" name="offer_letter_path" class="form-control">
        </div>

        <button class="btn btn-primary" type="submit"><i class="fa fa-upload"></i> Upload</button>
        <a class="btn btn-default" href="agency_dashboard.php">Back to dashboard</a>
    </form>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
