<?php
$pId = $project['id'];
$pName = $project['name'];
$pCode = $project['project_code'] ?? '';
$pStatus = $project['status'] ?? 'active';
$pValue = $project['project_value'] ?? 0;
$pCurrency = $project['currency'] ?? DEFAULT_CURRENCY;
$pDesc = $project['description'] ?? '';
$pLocation = $project['location'] ?? '';
$pClientName = $project['client_name'] ?? 'N/A';
$pCategoryName = $project['category_name'] ?? 'General';
$breadcrumb = [
    ['label' => 'Projects', 'url' => APP_URL . '/projects'],
    ['label' => $pName, 'url' => null]
];
ob_start();
?>
<div class="project-detail-container">
    <div class="page-header d-flex justify-between align-center mb-4">
        <div>
            <div class="d-flex align-center gap-2">
                <h1 class="page-title"><?= htmlspecialchars($pName) ?></h1>
                <span class="badge badge-<?= htmlspecialchars($pStatus) ?>"><?= strtoupper($pStatus) ?></span>
            </div>
            <p class="page-subtitle"><?= htmlspecialchars($pCode) ?> &bull; <?= htmlspecialchars($pCategoryName) ?> &bull; <?= htmlspecialchars($pClientName) ?></p>
        </div>
        <div class="d-flex gap-2">
            <a href="<?= APP_URL ?>/projects/<?= $pId ?>/edit" class="btn btn-secondary">
                <i class="fas fa-edit"></i> Edit Project
            </a>
            <a href="<?= APP_URL ?>/projects" class="btn btn-ghost">
                <i class="fas fa-arrow-left"></i> Back
            </a>
        </div>
    </div>

    <!-- Stat Cards -->
    <div class="stats-grid mb-4">
        <div class="stat-card">
            <div class="stat-icon bg-primary text-white"><i class="fas fa-coins"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?= formatCurrency((float)$pValue, $pCurrency) ?></div>
                <div class="stat-label">Project Budget</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-info text-white"><i class="fas fa-map-marker-alt"></i></div>
            <div class="stat-info">
                <div class="stat-value text-sm"><?= htmlspecialchars($pLocation ?: 'Not Specified') ?></div>
                <div class="stat-label">Location</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-success text-white"><i class="fas fa-user-tie"></i></div>
            <div class="stat-info">
                <div class="stat-value text-sm"><?= htmlspecialchars($pClientName) ?></div>
                <div class="stat-label">Client</div>
            </div>
        </div>
    </div>

    <!-- Project Content Card -->
    <div class="card mb-4">
        <div class="card-header">
            <div class="tabs">
                <div class="tab-item active" onclick="switchTab('overview')">Overview</div>
                <div class="tab-item" onclick="switchTab('contractors')">Contractors</div>
                <div class="tab-item" onclick="switchTab('milestones')">Milestones</div>
                <div class="tab-item" onclick="switchTab('documents')">Documents</div>
                <div class="tab-item" onclick="switchTab('finance')">Financial Analysis</div>
            </div>
        </div>
        <div class="card-body">
            <div id="tab-overview" class="tab-content active">
                <h4 class="fw-600 mb-2">Description</h4>
                <p class="text-secondary mb-4"><?= nl2br(htmlspecialchars($pDesc ?: 'No detailed description provided.')) ?></p>
                <?php if (!empty($project['managers'])): ?>
                <h4 class="fw-600 mb-2">Project Manager(s)</h4>
                <ul>
                    <?php foreach ($project['managers'] as $m): ?>
                    <li><?= htmlspecialchars($m['first_name'] . ' ' . $m['last_name']) ?> (<?= htmlspecialchars($m['email']) ?>)</li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>

            <div id="tab-contractors" class="tab-content">
                <?php if (empty($project['contractors'])): ?>
                    <p class="text-muted">No contractors assigned to this project yet.</p>
                    <form action="<?= APP_URL ?>/projects/<?= $pId ?>/assign-contractors" method="POST" class="mt-3">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                        <p class="text-sm text-secondary">Assign a contractor from the Edit Project screen.</p>
                    </form>
                <?php else: ?>
                <table class="table">
                    <thead><tr><th>Company</th><th>Code</th><th>Status</th><th>Response</th></tr></thead>
                    <tbody>
                        <?php foreach ($project['contractors'] as $c): ?>
                        <tr>
                            <td><a href="<?= APP_URL ?>/contractors/<?= $c['contractor_id'] ?>"><?= htmlspecialchars($c['company_name']) ?></a></td>
                            <td><?= htmlspecialchars($c['contractor_code']) ?></td>
                            <td><span class="badge badge-<?= $c['status'] === 'accepted' ? 'active' : ($c['status'] === 'rejected' ? 'cancelled' : 'draft') ?>"><?= ucfirst($c['status']) ?></span></td>
                            <td><?= htmlspecialchars($c['response_comment'] ?? '-') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <div id="tab-milestones" class="tab-content">
                <form action="<?= APP_URL ?>/projects/<?= $pId ?>/milestones/create" method="POST" class="d-flex gap-2 flex-wrap align-center mb-4">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                    <input type="text" name="title" placeholder="Milestone title" required class="form-control" style="flex:1;min-width:180px;">
                    <input type="date" name="due_date" required class="form-control" style="width:160px;">
                    <input type="text" name="description" placeholder="Description (optional)" class="form-control" style="flex:1;min-width:180px;">
                    <button type="submit" class="btn btn-primary">Add Milestone</button>
                </form>
                <?php if (empty($project['milestones'])): ?>
                    <p class="text-muted">No milestones yet.</p>
                <?php else: ?>
                <table class="table">
                    <thead><tr><th>Title</th><th>Due Date</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($project['milestones'] as $m): ?>
                        <tr>
                            <td><?= htmlspecialchars($m['title']) ?><?php if (!empty($m['description'])): ?><br><small class="text-muted"><?= htmlspecialchars($m['description']) ?></small><?php endif; ?></td>
                            <td><?= htmlspecialchars($m['due_date']) ?></td>
                            <td><span class="badge badge-<?= $m['status'] === 'completed' ? 'active' : 'draft' ?>"><?= ucfirst(str_replace('_',' ',$m['status'])) ?></span></td>
                            <td>
                                <?php if ($m['status'] !== 'completed'): ?>
                                <button type="button" class="btn btn-sm btn-secondary" onclick="markMilestoneComplete(<?= $m['id'] ?>)">Mark Complete</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <div id="tab-documents" class="tab-content">
                <form action="<?= APP_URL ?>/projects/<?= $pId ?>/upload-document" method="POST" enctype="multipart/form-data" class="d-flex gap-2 flex-wrap align-center mb-4">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                    <select name="document_type" class="form-control" style="width:180px;">
                        <option value="supporting">Supporting Document</option>
                        <option value="purchase_order">Purchase Order</option>
                        <option value="financial_analysis">Financial Analysis</option>
                        <option value="as_built">As-Built</option>
                    </select>
                    <input type="file" name="document" required class="form-control" style="flex:1;min-width:200px;">
                    <button type="submit" class="btn btn-primary">Upload</button>
                </form>
                <?php if (empty($project['documents'])): ?>
                    <p class="text-muted">No documents uploaded yet.</p>
                <?php else: ?>
                <table class="table">
                    <thead><tr><th>Name</th><th>Type</th><th>Size</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($project['documents'] as $doc): ?>
                        <tr>
                            <td><a href="<?= APP_URL ?>/uploads/<?= htmlspecialchars($doc['file_path']) ?>" target="_blank"><?= htmlspecialchars($doc['document_name']) ?></a></td>
                            <td><?= htmlspecialchars(ucwords(str_replace('_', ' ', $doc['document_type']))) ?></td>
                            <td><?= formatFileSize((int)$doc['file_size']) ?></td>
                            <td>
                                <form action="<?= APP_URL ?>/projects/documents/<?= $doc['id'] ?>/delete" method="POST" onsubmit="return confirm('Delete this document?');">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                                    <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <div id="tab-finance" class="tab-content">
                <?php if (!empty($finance)): ?>
                    <?php include __DIR__ . '/partials/financial_dashboard.php'; ?>
                <?php else: ?>
                    <p class="text-muted">No financial analysis document uploaded yet. Upload one from the Edit Project screen.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function switchTab(tabName) {
    document.querySelectorAll('.tab-item').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
    event.target.classList.add('active');
    document.getElementById('tab-' + tabName).classList.add('active');
}

function markMilestoneComplete(id) {
    fetch('<?= APP_URL ?>/projects/milestones/' + id + '/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'status=completed&csrf_token=' + encodeURIComponent('<?= $_SESSION[CSRF_TOKEN_NAME] ?? '' ?>')
    }).then(() => location.reload());
}
</script>
<?php
$content = ob_get_clean();
$pageTitle = $pName;
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>
