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

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

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

include 'delete_file_handler.php';

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

$user_id = (int) ($_SESSION['user_id'] ?? 0);
$full_name = trim($_SESSION['full_name'] ?? 'User');

$hasCompanyWorkspace = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== '';
$active_company_id = $hasCompanyWorkspace ? (int) $_SESSION['active_company_id'] : null;
$company_name = trim($_SESSION['company_name'] ?? '');

$workspace = $_GET['workspace'] ?? 'personal';
$scope = $_GET['scope'] ?? $workspace;

if ($workspace !== 'company' || !$hasCompanyWorkspace) {
    $workspace = 'personal';
}

if ($scope !== 'company' || !$hasCompanyWorkspace) {
    $scope = 'personal';
}

$is_company_workspace = ($workspace === 'company' && $scope === 'company' && $active_company_id !== null);

$message = '';
$error = '';

/*
|--------------------------------------------------------------------------
| Create folder
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_folder'])) {
    $folder_name = trim($_POST['folder_name'] ?? '');

    if ($folder_name === '') {
        $error = 'Please enter folder name.';
    } else {
        try {
            if ($is_company_workspace) {
                $stmt = $db->prepare("
                    INSERT INTO folders (folder_name, user_id, company_id, created_at)
                    VALUES (:folder_name, NULL, :company_id, NOW())
                ");
                $stmt->bindValue(':folder_name', $folder_name, PDO::PARAM_STR);
                $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
            } else {
                $stmt = $db->prepare("
                    INSERT INTO folders (folder_name, user_id, company_id, created_at)
                    VALUES (:folder_name, :user_id, NULL, NOW())
                ");
                $stmt->bindValue(':folder_name', $folder_name, PDO::PARAM_STR);
                $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            }

            $stmt->execute();
            $message = 'Folder created successfully.';
        } catch (PDOException $e) {
            $error = 'Unable to create folder: ' . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| Load folders
|--------------------------------------------------------------------------
*/
try {
    if ($is_company_workspace) {
        $stmt = $db->prepare("
            SELECT id, folder_name, created_at
            FROM folders
            WHERE company_id = :company_id
            ORDER BY id DESC
        ");
        $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
    } else {
        $stmt = $db->prepare("
            SELECT id, folder_name, created_at
            FROM folders
            WHERE user_id = :user_id
              AND company_id IS NULL
            ORDER BY id DESC
        ");
        $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    }

    $stmt->execute();
    $folders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die('Folder query error: ' . $e->getMessage());
}

$pageTitle = $is_company_workspace ? 'Company Folders' : 'Personal Folders';
$pageText = $is_company_workspace
    ? 'Manage shared company folders.'
    : 'Manage your personal folders.';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Folders</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <style>
        
        


     
        

        .form-row {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .form-row input {
            flex: 1;
            min-width: 220px;
        }

        .alert-success {
            background: #ecfdf3;
            color: #027a48;
            border: 1px solid #abefc6;
            padding: 12px 14px;
            border-radius: 14px;
            margin-bottom: 16px;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
            border: 1px solid #fecdca;
            padding: 12px 14px;
            border-radius: 14px;
            margin-bottom: 16px;
        }

        .empty-state {
            background: #fff;
            border: 1px dashed #cbd5e1;
            border-radius: 20px;
            padding: 28px;
            text-align: center;
            color: #64748b;
        }
        

.folder-link:hover {
    transform: translateY(-3px);
    box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08);
}

.folder-grid {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.folder-link {
    display: block;
    text-decoration: none;
    color: inherit;
}

.folder-card {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border-radius: 10px;
    background: rgba(255,255,255,0.04);
    border: 1px solid rgba(255,255,255,0.06);
    box-shadow: none;
}

.folder-card:hover {
    background: rgba(255,255,255,0.08);
    transform: none;
    box-shadow: none;
}

.folder-name {
    font-size: 14px;
    font-weight: 600;
    margin: 0;
}

.folder-meta {
    display: none;
}

        @media (max-width: 1100px) {
            .folder-grid {
                grid-template-columns: 1fr 1fr;
            }
        }

        @media (max-width: 700px) {
            .folder-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="page-shell">

            <section class="hero">
                <div class="hero-top">
                    <div>
                        <h1><?php echo htmlspecialchars($pageTitle); ?></h1>
                        <p><?php echo htmlspecialchars($pageText); ?></p>
                    </div>

                    <div class="welcome-badge">
                        <?php echo $is_company_workspace
                            ? htmlspecialchars($company_name !== '' ? $company_name : 'Company Workspace')
                            : 'Personal Workspace'; ?>
                    </div>
                </div>
            </section>

            <div class="content-card" style="margin-bottom: 20px;">
                <div class="section-title">Create Folder</div>
                <div class="section-subtext">
                    <?php echo $is_company_workspace
                        ? 'Create a shared company folder.'
                        : 'Create a personal folder for your own files.'; ?>
                </div>

                <?php if ($message !== ''): ?>
                    <div class="alert-success"><?php echo htmlspecialchars($message); ?></div>
                <?php endif; ?>

                <?php if ($error !== ''): ?>
                    <div class="alert-danger"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>

                <form method="POST">
                    <div class="form-row">
                        <input type="text" name="folder_name" placeholder="Enter folder name" required>
                        <button type="submit" name="create_folder" class="btn btn-primary">+ Create Folder</button>
                    </div>
                </form>
            </div>

            <?php if (!empty($folders)): ?>
                <div class="folder-grid">
                    <?php foreach ($folders as $folder): ?>
                        <a href="folder_view.php?id=<?php echo (int)$folder['id']; ?>&workspace=<?php echo urlencode($workspace); ?>&scope=<?php echo urlencode($scope); ?>" class="folder-card folder-link">
                            <div class="folder-name">
                                <span style="opacity:0.7;">📂</span>
                                <?php echo htmlspecialchars($folder['folder_name']); ?>
                            </div>
                            <div class="folder-meta">
                                Created:
                                <?php echo htmlspecialchars(date('d/m/Y', strtotime($folder['created_at']))); ?>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    No folders found in this workspace.
                </div>
            <?php endif; ?>

        </div>
    </main>
</div>
</body>
</html>