<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('projects.manage');

require_once __DIR__ . '/../config/database.php';

requirePermission('manage_projects');

/* =============================
   GENERATE PROJECT CODE
============================= */

$year = date('Y');
$count = $pdo->query("SELECT COUNT(*) FROM projects")->fetchColumn() + 1;
$projectCode = "EDM-" . $year . "-" . str_pad($count, 4, '0', STR_PAD_LEFT);

/* =============================
   FETCH CLIENT COMPANIES
============================= */

$companies = $pdo->query("
    SELECT id, company_name
    FROM companies
    ORDER BY company_name ASC
")->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   HANDLE SUBMIT
============================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $projectName = trim($_POST['project_name']);
    $clientId    = (int)$_POST['client_company_id'];
    $type        = $_POST['project_type'];
    $budget      = $_POST['budget'] ?: null;
    $startDate   = $_POST['start_date'] ?: null;
    $endDate     = $_POST['expected_end_date'] ?: null;
    $status      = $_POST['status'];

    if (!$projectName) {
        die("Project name is required.");
    }

    $stmt = $pdo->prepare("
        INSERT INTO projects
        (project_code, project_name, client_company_id,
         project_type, budget, start_date,
         expected_end_date, status, created_by_user_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $projectCode,
        $projectName,
        $clientId ?: null,
        $type,
        $budget,
        $startDate,
        $endDate,
        $status,
        $_SESSION['user_id']
    ]);

    header("Location: projects.php");
    exit;
}

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

<div class="page-header">
    <h2>Add Project</h2>
    <p class="page-subtitle">
        Create new enterprise project (Metering + Electrical Scope)
    </p>
</div>

<form method="POST" class="card-form">

    <label>Project Code</label>
    <input type="text"
           value="<?= htmlspecialchars($projectCode) ?>"
           disabled>

    <label>Project Name *</label>
    <input type="text"
           name="project_name"
           required>

    <label>Client Company</label>
    <select name="client_company_id">
        <option value="">Select Client</option>
        <?php foreach ($companies as $c): ?>
            <option value="<?= $c['id'] ?>">
                <?= htmlspecialchars($c['company_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <label>Project Type</label>
    <select name="project_type" required>
        <option value="METERING">Metering</option>
        <option value="ELECTRICAL">Electrical Installation</option>
        <option value="HYBRID">Metering + Electrical</option>
    </select>

    <label>Estimated Budget (Optional)</label>
    <input type="number"
           name="budget"
           step="0.01"
           placeholder="0.00">

    <label>Start Date</label>
    <input type="date" name="start_date">

    <label>Expected End Date</label>
    <input type="date" name="expected_end_date">

    <label>Status</label>
    <select name="status">
        <option value="PLANNING">Planning</option>
        <option value="ACTIVE">Active</option>
        <option value="ON_HOLD">On Hold</option>
        <option value="COMPLETED">Completed</option>
        <option value="CANCELLED">Cancelled</option>
    </select>

    <button type="submit" class="btn-primary">
        Create Project
    </button>

</form>

</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>