<?php
$isEdit = isset($project) && !empty($project);
$pageTitle = $isEdit ? 'Edit Project' : 'Create New Project';
$breadcrumb = [
    ['label' => 'Projects', 'url' => APP_URL . '/projects'],
    ['label' => $pageTitle, 'url' => null]
];
$vendorType = $project['implementing_vendor_type'] ?? 'in_house';
$assignedContractorIds = array_map(fn($c) => (int)$c['contractor_id'], $project['contractors'] ?? []);
ob_start();
?>
<div class="max-w-5xl mx-auto">
<h1 class="text-2xl font-bold text-gray-800 mb-6"><?= $pageTitle ?></h1>

<form action="<?= APP_URL ?>/projects<?= $isEdit ? '/' . $project['id'] . '/edit' : '/create' ?>" method="POST" enctype="multipart/form-data" class="bg-white p-8 rounded-lg shadow space-y-8">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">

    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
        <!-- Section 1 -->
        <div>
            <h2 class="text-lg font-semibold mb-4 border-b pb-2">1. Basic Info</h2>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Project Name *</label>
                <input type="text" name="name" value="<?= htmlspecialchars($project['name'] ?? '') ?>" required class="w-full border rounded p-2">
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Client *</label>
                <select name="client_id" required class="w-full border rounded p-2">
                    <option value="">Select Client</option>
                    <?php foreach ($clients as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= (int)($project['client_id'] ?? 0) === (int)$c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['company_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Category</label>
                <select name="category_id" class="w-full border rounded p-2">
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>" <?= (int)($project['category_id'] ?? 0) === (int)$cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Description</label>
                <textarea name="description" class="w-full border rounded p-2" rows="3"><?= htmlspecialchars($project['description'] ?? '') ?></textarea>
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Location</label>
                <input type="text" name="location" value="<?= htmlspecialchars($project['location'] ?? '') ?>" class="w-full border rounded p-2">
            </div>
            <div class="grid grid-cols-2 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 font-bold mb-2">Start Date</label>
                    <input type="date" name="start_date" value="<?= htmlspecialchars($project['start_date'] ?? '') ?>" class="w-full border rounded p-2">
                </div>
                <div>
                    <label class="block text-gray-700 font-bold mb-2">Expected End Date</label>
                    <input type="date" name="expected_end_date" value="<?= htmlspecialchars($project['expected_end_date'] ?? '') ?>" class="w-full border rounded p-2">
                </div>
            </div>
            <div class="grid grid-cols-2 gap-4 mb-4">
                <div>
                    <label class="block text-gray-700 font-bold mb-2">Currency</label>
                    <select name="currency" class="w-full border rounded p-2">
                        <?php foreach (getCurrencies() as $code => $symbol): ?>
                        <option value="<?= $code ?>" <?= ($project['currency'] ?? DEFAULT_CURRENCY) === $code ? 'selected' : '' ?>><?= $code ?> (<?= $symbol ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 font-bold mb-2">Project Value</label>
                    <input type="number" name="project_value" step="0.01" value="<?= htmlspecialchars($project['project_value'] ?? '') ?>" class="w-full border rounded p-2">
                </div>
            </div>
            <?php if ($isEdit): ?>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Status</label>
                <select name="status" class="w-full border rounded p-2">
                    <?php foreach (['draft', 'active', 'on_hold', 'completed', 'cancelled'] as $st): ?>
                    <option value="<?= $st ?>" <?= ($project['status'] ?? '') === $st ? 'selected' : '' ?>><?= ucfirst(str_replace('_', ' ', $st)) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
        </div>

        <!-- Section 2 & 3 -->
        <div>
            <h2 class="text-lg font-semibold mb-4 border-b pb-2">2. Implementation</h2>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Vendor Type</label>
                <div class="flex items-center gap-4">
                    <label><input type="radio" name="implementing_vendor_type" value="in_house" <?= $vendorType === 'in_house' ? 'checked' : '' ?> onchange="toggleVendor(this.value)"> In-House</label>
                    <label><input type="radio" name="implementing_vendor_type" value="external" <?= $vendorType === 'external' ? 'checked' : '' ?> onchange="toggleVendor(this.value)"> External Contractor</label>
                </div>
            </div>

            <div id="pm_section" class="mb-4 <?= $vendorType === 'external' ? 'hidden' : '' ?>">
                <label class="block text-gray-700 font-bold mb-2">Project Manager</label>
                <select name="project_manager_id" class="w-full border rounded p-2">
                    <option value="">Select PM</option>
                    <?php foreach ($managers ?? [] as $m): ?>
                    <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['first_name'] . ' ' . $m['last_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div id="contractor_section" class="mb-4 <?= $vendorType === 'in_house' ? 'hidden' : '' ?>">
                <label class="block text-gray-700 font-bold mb-2">Contractors (select one or more)</label>
                <div class="border rounded p-2 max-h-40 overflow-y-auto">
                    <?php if (empty($contractors)): ?>
                        <p class="text-sm text-gray-500">No approved contractors available yet.</p>
                    <?php endif; ?>
                    <?php foreach ($contractors ?? [] as $c): ?>
                    <label class="block py-1"><input type="checkbox" name="contractors[]" value="<?= $c['id'] ?>" <?= in_array((int)$c['id'], $assignedContractorIds, true) ? 'checked' : '' ?>> <?= htmlspecialchars($c['company_name']) ?></label>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Reporting Template</label>
                <select name="report_template_id" class="w-full border rounded p-2">
                    <option value="">Select Template</option>
                    <?php foreach ($templates ?? [] as $t): ?>
                    <option value="<?= $t['id'] ?>" <?= (int)($project['report_template_id'] ?? 0) === (int)$t['id'] ? 'selected' : '' ?>><?= htmlspecialchars($t['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <?php if (!$isEdit): ?>
            <h2 class="text-lg font-semibold mb-4 mt-8 border-b pb-2">3. Documents</h2>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Purchase Order</label>
                <input type="file" name="purchase_order" class="w-full border rounded p-2">
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Financial Analysis (Excel)</label>
                <input type="file" name="financial_analysis" accept=".xlsx,.xls" class="w-full border rounded p-2">
                <p class="text-sm text-gray-500">Columns: Category, Item Name, Unit, Quantity, Unit Rate.</p>
            </div>
            <div class="mb-4">
                <label class="block text-gray-700 font-bold mb-2">Supporting Documents</label>
                <input type="file" name="supporting_documents[]" multiple class="w-full border rounded p-2">
            </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="mt-8 text-right">
        <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-6 rounded shadow text-lg">Save Project</button>
    </div>
</form>
</div>

<script>
function toggleVendor(type) {
    if (type === 'in_house') {
        document.getElementById('pm_section').classList.remove('hidden');
        document.getElementById('contractor_section').classList.add('hidden');
    } else {
        document.getElementById('pm_section').classList.add('hidden');
        document.getElementById('contractor_section').classList.remove('hidden');
    }
}
</script>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>
