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

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

$success = isset($_GET['success']) ? "Project created successfully!" : "";
$error = "";

// Handle Project Delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delete_id = (int)$_GET['delete'];
    try {
        $conn->begin_transaction();
        
        // Delete attachments files
        $files = $conn->query("SELECT file_path FROM project_attachments WHERE project_id = $delete_id");
        while ($f = $files->fetch_assoc()) {
            $full_path = "../" . $f['file_path'];
            if (file_exists($full_path)) unlink($full_path);
        }
        
        // Delete project (cascading will handle milestones & attachments)
        $conn->query("DELETE FROM project_master WHERE id = $delete_id");
        
        $conn->commit();
        header("Location: project-management.php?success=Project deleted successfully");
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        $error = "Failed to delete project.";
    }
}

// Fetch All Projects with Manager Count
$projects_result = $conn->query("
    SELECT p.*, 
           (SELECT COUNT(*) FROM project_managers WHERE project_id = p.id) as manager_count,
           (SELECT GROUP_CONCAT(u.full_name SEPARATOR ', ') 
            FROM project_managers pm 
            JOIN users u ON pm.user_id = u.id 
            WHERE pm.project_id = p.id) as managers
    FROM project_master p
    ORDER BY p.created_at DESC
");

$projects = $projects_result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 1300px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
            position: relative;
        }
        .header h1 {
            font-size: clamp(28px, 5.5vw, 42px);
            font-weight: 700;
        }

        .top-bar {
            padding: 25px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            background: rgba(255,255,255,0.05);
        }

        .search-box {
            flex: 1;
            min-width: 280px;
        }
        .search-box input {
            width: 100%;
            padding: 14px 20px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }

        .add-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 14px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 10px 25px rgba(168,85,247,0.4);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        th {
            background: rgba(168,85,247,0.3);
            padding: 18px 16px;
            text-align: left;
            font-weight: 600;
        }
        td {
            padding: 18px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .status-badge {
            padding: 8px 18px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 700;
        }
        .status-Planning { background:#8b5cf6; color:white; }
        .status-InProgress, .status-Active { background:#22c55e; color:white; }
        .status-OnHold { background:#f59e0b; color:white; }
        .status-Completed { background:#15803d; color:white; }
        .status-Cancelled { background:#ef4444; color:white; }

        .action-btns a {
            margin: 0 6px;
            padding: 8px 14px;
            border-radius: 10px;
            text-decoration: none;
            font-size: 0.95rem;
        }
        .btn-view { background:rgba(59,130,246,0.2); color:#60a5fa; }
        .btn-edit { background:rgba(234,179,8,0.2); color:#fde047; }
        .btn-delete { 
            background:rgba(239,68,68,0.2); 
            color:#f87171; 
        }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin: 20px 40px;
            font-weight: 600;
        }
        .success { background:rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }

        @media (max-width: 768px) {
            .top-bar { flex-direction: column; align-items: stretch; }
            table { font-size: 0.95rem; }
            th, td { padding: 14px 10px; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">

        <div class="header">
            <h1><i class="fas fa-project-diagram"></i> Project Management</h1>
            <p style="margin-top:12px; opacity:0.9;">Manage all your projects in one place</p>
        </div>

        <div class="top-bar">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search projects by name, code or client..." onkeyup="filterTable()">
            </div>
            <a href="add-project.php" class="add-btn">
                <i class="fas fa-plus"></i> Add New Project
            </a>
        </div>

        <?php if ($success): ?>
            <div class="message success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="message" style="background:rgba(239,68,68,0.25); color:#fca5a5;"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div style="padding:0 40px 40px;">
            <?php if (empty($projects)): ?>
                <div style="text-align:center; padding:80px 20px; color:#94a3b8;">
                    <i class="fas fa-folder-open" style="font-size:4rem; opacity:0.3; margin-bottom:20px;"></i>
                    <h3>No projects found</h3>
                    <p>Create your first project to get started.</p>
                </div>
            <?php else: ?>
                <table id="projectTable">
                    <thead>
                        <tr>
                            <th>Project Code</th>
                            <th>Project Name</th>
                            <th>Client</th>
                            <th>Managers</th>
                            <th>Status</th>
                            <th style="text-align:center;">Actions</th>
                            <!-- <th>Project Dashboard</th> -->
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($projects as $p): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($p['project_code']) ?></strong></td>
                            <td><?= htmlspecialchars($p['project_name']) ?></td>
                            <td><?= htmlspecialchars($p['client_name'] ?? '—') ?></td>
                            <td>
                                <?= $p['managers'] ? htmlspecialchars($p['managers']) : '<span style="color:#64748b;">Not Assigned</span>' ?>
                                <small>(<?= $p['manager_count'] ?>)</small>
                            </td>
                            <td>
                                <span class="status-badge status-<?= str_replace(' ', '', htmlspecialchars($p['project_status'])) ?>">
                                    <?= htmlspecialchars($p['project_status']) ?>
                                </span>
                            </td>
                            <td class="action-btns" style="text-align:center; white-space:nowrap;">
                                <a href="view-project.php?id=<?= $p['id'] ?>" class="btn-view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="edit-project.php?id=<?= $p['id'] ?>" class="btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="project-management.php?delete=<?= $p['id'] ?>" 
                                   class="btn-delete" 
                                   title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this project? All related data (milestones & attachments) will also be deleted permanently.')">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function filterTable() {
    const input = document.getElementById("searchInput").value.toLowerCase();
    const rows = document.querySelectorAll("#projectTable tbody tr");

    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(input) ? "" : "none";
    });
}
</script>

</body>
</html>

<?php $conn->close(); ?>