<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') === 'guest') {
    header("Location: login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: my_documents.php");
    exit;
}

$folderName = trim($_POST['folder_name'] ?? '');
$workspace = trim($_POST['workspace'] ?? 'personal');
$requested_company_id = (int)($_POST['company_id'] ?? 0);

$parentFolderId = isset($_POST['parent_folder_id']) && $_POST['parent_folder_id'] !== ''
    ? (int)$_POST['parent_folder_id']
    : null;

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$userId = (int)($_SESSION['user_id'] ?? 0);

$isCompanyWorkspace = false;
$activeCompanyId = null;

if ($workspace === 'company' && $requested_company_id > 0) {
    $stmtCompany = $db->prepare("
        SELECT c.id
        FROM company_users cu
        INNER JOIN companies c ON c.id = cu.company_id
        WHERE cu.user_id = :user_id
          AND cu.company_id = :company_id
        LIMIT 1
    ");
    $stmtCompany->bindValue(':user_id', $userId, PDO::PARAM_INT);
    $stmtCompany->bindValue(':company_id', $requested_company_id, PDO::PARAM_INT);
    $stmtCompany->execute();

    $companyRow = $stmtCompany->fetch(PDO::FETCH_ASSOC);

    if ($companyRow) {
        $isCompanyWorkspace = true;
        $activeCompanyId = (int)$companyRow['id'];
    }
}

if ($folderName === '') {
    if ($parentFolderId && $parentFolderId > 0) {
        $redirect = "folder_view.php?id=" . $parentFolderId .
            "&workspace=" . urlencode($isCompanyWorkspace ? 'company' : 'personal') .
            "&scope=" . urlencode($isCompanyWorkspace ? 'company' : 'personal');

        if ($isCompanyWorkspace && !empty($activeCompanyId)) {
            $redirect .= "&company_id=" . (int)$activeCompanyId;
        }

        header("Location: " . $redirect);
    } else {
        $redirect = "my_documents.php?workspace=" . urlencode($isCompanyWorkspace ? 'company' : 'personal') .
            "&scope=" . urlencode($isCompanyWorkspace ? 'company' : 'personal');

        if ($isCompanyWorkspace && !empty($activeCompanyId)) {
            $redirect .= "&company_id=" . (int)$activeCompanyId;
        }

        header("Location: " . $redirect);
    }
    exit;
}

try {
    if ($isCompanyWorkspace) {
        if ($parentFolderId && $parentFolderId > 0) {
            $check = $db->prepare("
                SELECT id
                FROM folders
                WHERE id = :id
                  AND company_id = :company_id
                LIMIT 1
            ");
            $check->bindValue(':id', $parentFolderId, PDO::PARAM_INT);
            $check->bindValue(':company_id', $activeCompanyId, PDO::PARAM_INT);
            $check->execute();

            if (!$check->fetch(PDO::FETCH_ASSOC)) {
                die("Invalid parent folder.");
            }
        }

        $stmt = $db->prepare("
            INSERT INTO folders (folder_name, company_id, user_id, parent_folder_id)
            VALUES (:folder_name, :company_id, NULL, :parent_folder_id)
        ");
        $stmt->bindValue(':folder_name', $folderName, PDO::PARAM_STR);
        $stmt->bindValue(':company_id', $activeCompanyId, PDO::PARAM_INT);

        if ($parentFolderId && $parentFolderId > 0) {
            $stmt->bindValue(':parent_folder_id', $parentFolderId, PDO::PARAM_INT);
        } else {
            $stmt->bindValue(':parent_folder_id', null, PDO::PARAM_NULL);
        }

        $stmt->execute();

        if ($parentFolderId && $parentFolderId > 0) {
            header("Location: folder_view.php?id=" . $parentFolderId . "&workspace=company&scope=company&company_id=" . (int)$activeCompanyId);
        } else {
            header("Location: my_documents.php?workspace=company&scope=company&company_id=" . (int)$activeCompanyId);
        }
        exit;
    }

    if ($parentFolderId && $parentFolderId > 0) {
        $check = $db->prepare("
            SELECT id
            FROM folders
            WHERE id = :id
              AND user_id = :user_id
              AND company_id IS NULL
            LIMIT 1
        ");
        $check->bindValue(':id', $parentFolderId, PDO::PARAM_INT);
        $check->bindValue(':user_id', $userId, PDO::PARAM_INT);
        $check->execute();

        if (!$check->fetch(PDO::FETCH_ASSOC)) {
            die("Invalid parent folder.");
        }
    }

    $stmt = $db->prepare("
        INSERT INTO folders (folder_name, user_id, company_id, parent_folder_id)
        VALUES (:folder_name, :user_id, NULL, :parent_folder_id)
    ");
    $stmt->bindValue(':folder_name', $folderName, PDO::PARAM_STR);
    $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);

    if ($parentFolderId && $parentFolderId > 0) {
        $stmt->bindValue(':parent_folder_id', $parentFolderId, PDO::PARAM_INT);
    } else {
        $stmt->bindValue(':parent_folder_id', null, PDO::PARAM_NULL);
    }

    $stmt->execute();

    if ($parentFolderId && $parentFolderId > 0) {
        header("Location: folder_view.php?id=" . $parentFolderId . "&workspace=personal&scope=personal");
    } else {
        header("Location: my_documents.php?workspace=personal&scope=personal");
    }
    exit;

} catch (PDOException $e) {
    die("Error creating folder: " . $e->getMessage());
}