<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_financials.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/project_menu.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();

$pdo = crm_pdo();
$page_title = 'Project';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';

if ($id > 0) {
    gp_require_project_edit($pdo, $id);
} else {
    gp_require_project_create($pdo);
}

$item = [
    'code' => '',
    'title' => '',
    'customer_id' => '',
    'category_id' => '',
    'status' => 'new',
    'address' => '',
    'city' => '',
    'start_date' => '',
    'end_date_planned' => '',
    'end_date_actual' => '',
    'budget' => '',
    'installation_cost' => '',
    'notes' => '',
];

$errors = [];
$customers = $pdo->query("SELECT id, name FROM customers WHERE active = 1 ORDER BY name ASC")->fetchAll();
$cats = $pdo->query("SELECT id, name FROM project_categories WHERE is_active = 1 ORDER BY name ASC")->fetchAll();
$statuses = gp_project_statuses($pdo, true);

if ($id) {
    $st = $pdo->prepare("SELECT code, title, customer_id, category_id, status, address, city, start_date, end_date_planned, end_date_actual, budget, installation_cost, notes FROM projects WHERE id = :id LIMIT 1");
    $st->execute([':id' => $id]);
    $row = $st->fetch();
    if ($row) $item = array_merge($item, $row);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) gp_require_project_edit($pdo, $id);

    foreach (array_keys($item) as $k) {
        $item[$k] = trim((string)($_POST[$k] ?? ''));
    }

    if ($item['title'] === '') $errors[] = 'Title is required.';
    if ($item['customer_id'] === '') $errors[] = 'Customer is required.';
    if (!array_key_exists($item['status'], $statuses)) $errors[] = 'Invalid status.';
    if ($item['code'] === '') $item['code'] = 'PRJ-' . date('Ymd-His');

    if (!$errors) {
        $params = [
            ':code' => $item['code'],
            ':title' => $item['title'],
            ':customer_id' => $item['customer_id'],
            ':category_id' => $item['category_id'] !== '' ? $item['category_id'] : null,
            ':status' => $item['status'],
            ':address' => $item['address'] !== '' ? $item['address'] : null,
            ':city' => $item['city'] !== '' ? $item['city'] : null,
            ':start_date' => $item['start_date'] !== '' ? $item['start_date'] : null,
            ':end_date_planned' => $item['end_date_planned'] !== '' ? $item['end_date_planned'] : null,
            ':end_date_actual' => $item['end_date_actual'] !== '' ? $item['end_date_actual'] : null,
            ':budget' => $item['budget'] !== '' ? $item['budget'] : null,
            ':installation_cost' => $item['installation_cost'] !== '' ? $item['installation_cost'] : null,
            ':notes' => $item['notes'] !== '' ? $item['notes'] : null,
        ];

        if ($id > 0) {
            $sql = "UPDATE projects SET code = :code, title = :title, customer_id = :customer_id, category_id = :category_id, status = :status, address = :address, city = :city, start_date = :start_date, end_date_planned = :end_date_planned, end_date_actual = :end_date_actual, budget = :budget, installation_cost = :installation_cost, notes = :notes WHERE id = :id";
            $params[':id'] = $id;
        } else {
            $sql = "INSERT INTO projects (code, title, customer_id, category_id, status, address, city, start_date, end_date_planned, end_date_actual, budget, installation_cost, notes) VALUES (:code, :title, :customer_id, :category_id, :status, :address, :city, :start_date, :end_date_planned, :end_date_actual, :budget, :installation_cost, :notes)";
        }

        $st = $pdo->prepare($sql);
        $ok = $st->execute($params);

        if (!$ok) {
            $info = $st->errorInfo();
            $errors[] = 'Save failed: ' . ($info[2] ?? 'Unknown database error.');
        } else {
            if (!$id) $id = (int)$pdo->lastInsertId();
            header('Location: /public/projects/edit.php?id=' . $id . '&saved=1');
            exit;
        }
    }
}

$summary = $id > 0 ? gp_project_financial_summary($pdo, $id) : [
    'equipment_cost'=>0,'installation_cost'=>0,'partner_cost'=>0,'expense_cost'=>0,'labor_cost'=>0,
    'direct_cost'=>0,'payments_in'=>0,'budget'=>0,'margin'=>0,'estimated_revenue'=>0
];
$customerBalance = (float)($summary['balance'] ?? ((float)$summary['budget'] - (float)$summary['payments_in']));
$profit = (float)($summary['profit'] ?? $summary['margin'] ?? 0);

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title"><h1><?php echo $id ? 'Edit project' : 'New project'; ?></h1></div>
</div>

<?php if ($id) gp_render_project_menu($pdo, $id); ?>

<div class="grid-2">
  <div class="card">
    <?php if ($saved): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)">Project saved successfully.</div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="id" value="<?php echo (int)$id; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Code</label><input name="code" value="<?php echo h($item['code']); ?>"></div>
        <div class="form-group"><label>Title</label><input name="title" value="<?php echo h($item['title']); ?>"></div>
        <div class="form-group">
          <label>Customer</label>
          <select name="customer_id">
            <option value="">Select...</option>
            <?php foreach ($customers as $c): ?><option value="<?php echo (int)$c['id']; ?>" <?php echo ((string)$item['customer_id'] === (string)$c['id']) ? 'selected' : ''; ?>><?php echo h($c['name']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Category</label>
          <select name="category_id">
            <option value="">-</option>
            <?php foreach ($cats as $c): ?><option value="<?php echo (int)$c['id']; ?>" <?php echo ((string)$item['category_id'] === (string)$c['id']) ? 'selected' : ''; ?>><?php echo h($c['name']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Status</label>
          <select name="status">
            <?php foreach ($statuses as $key => $label): ?><option value="<?php echo h($key); ?>" <?php echo ($item['status'] === $key) ? 'selected' : ''; ?>><?php echo h($label); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group"><label>Budget / sold price</label><input name="budget" value="<?php echo h($item['budget']); ?>"></div>
        <div class="form-group"><label>Installation cost</label><input name="installation_cost" value="<?php echo h($item['installation_cost']); ?>"></div>
        <div class="form-group"><label>Address</label><input name="address" value="<?php echo h($item['address']); ?>"></div>
        <div class="form-group"><label>City</label><input name="city" value="<?php echo h($item['city']); ?>"></div>
        <div class="form-group"><label>Start date</label><input type="date" name="start_date" value="<?php echo h($item['start_date']); ?>"></div>
        <div class="form-group"><label>Planned end</label><input type="date" name="end_date_planned" value="<?php echo h($item['end_date_planned']); ?>"></div>
        <div class="form-group"><label>Actual end</label><input type="date" name="end_date_actual" value="<?php echo h($item['end_date_actual']); ?>"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"><?php echo h($item['notes']); ?></textarea></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Save project</button><a class="btn btn-secondary" href="/public/projects/index.php">Back</a></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Project financial summary</h1><span>Stable project workflow</span></div>
    <div class="table-responsive">
      <table class="table">
        <tbody>
          <tr><td>Budget / sold price</td><td>€ <?php echo h(number_format((float)$summary['budget'], 2)); ?></td></tr>
          <tr><td>Payments received</td><td>€ <?php echo h(number_format((float)$summary['payments_in'], 2)); ?></td></tr>
          <tr><td><strong>Customer balance</strong></td><td><strong>€ <?php echo h(number_format($customerBalance, 2)); ?></strong></td></tr>
          <tr><td>Equipment cost</td><td>€ <?php echo h(number_format((float)$summary['equipment_cost'], 2)); ?></td></tr>
          <tr><td>Installation cost</td><td>€ <?php echo h(number_format((float)$summary['installation_cost'], 2)); ?></td></tr>
          <tr><td>Labor cost total</td><td>€ <?php echo h(number_format((float)$summary['labor_cost'], 2)); ?></td></tr>
          <tr><td>Employee expenses</td><td>€ <?php echo h(number_format((float)$summary['employee_expense_cost'], 2)); ?></td></tr>
          <tr><td>External partner cost</td><td>€ <?php echo h(number_format((float)$summary['partner_cost'], 2)); ?></td></tr>
          <tr><td>Project expenses</td><td>€ <?php echo h(number_format((float)$summary['expense_cost'], 2)); ?></td></tr>
          <tr><td><strong>Final project cost</strong></td><td><strong>€ <?php echo h(number_format((float)$summary['direct_cost'], 2)); ?></strong></td></tr>
          <tr><td><strong>Total profit</strong></td><td><strong>€ <?php echo h(number_format($profit, 2)); ?></strong></td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
