<?php
require_once __DIR__ . '/../../app/core/bootstrap.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 = 'Sold Equipment';

$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
gp_require_project_edit($pdo, $projectId);

$stmt = $pdo->prepare("SELECT p.*, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id WHERE p.id = :id LIMIT 1");
$stmt->execute([':id' => $projectId]);
$project = $stmt->fetch();
if (!$project) die('Project not found.');

$errors = [];
$ok = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    if (($_POST['action'] ?? '') === 'delete') {
        $rowId = (int)($_POST['row_id'] ?? 0);
        $stmt = $pdo->prepare("DELETE FROM project_sold_equipment WHERE id = :id AND project_id = :pid");
        $stmt->execute([':id' => $rowId, ':pid' => $projectId]);
        $ok = 'Equipment item deleted.';
    } else {
        $itemName = trim((string)($_POST['item_name'] ?? ''));
        $brand = trim((string)($_POST['brand'] ?? ''));
        $model = trim((string)($_POST['model'] ?? ''));
        $serial = trim((string)($_POST['serial_number'] ?? ''));
        $purchaseDate = trim((string)($_POST['purchase_date'] ?? ''));
        $wStart = trim((string)($_POST['warranty_start'] ?? ''));
        $wEnd = trim((string)($_POST['warranty_end'] ?? ''));
        $supplier = trim((string)($_POST['supplier_name'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($itemName === '') $errors[] = 'Item name is required.';
        if ((int)$project['customer_id'] <= 0) $errors[] = 'Project has no customer linked.';

        if (!$errors) {
            $stmt = $pdo->prepare("
                INSERT INTO project_sold_equipment
                    (project_id, customer_id, item_name, brand, model, serial_number, purchase_date, warranty_start, warranty_end, supplier_name, notes)
                VALUES
                    (:project_id, :customer_id, :item_name, :brand, :model, :serial_number, :purchase_date, :warranty_start, :warranty_end, :supplier_name, :notes)
            ");
            $stmt->execute([
                ':project_id' => $projectId,
                ':customer_id' => (int)$project['customer_id'],
                ':item_name' => $itemName,
                ':brand' => $brand !== '' ? $brand : null,
                ':model' => $model !== '' ? $model : null,
                ':serial_number' => $serial !== '' ? $serial : null,
                ':purchase_date' => $purchaseDate !== '' ? $purchaseDate : null,
                ':warranty_start' => $wStart !== '' ? $wStart : null,
                ':warranty_end' => $wEnd !== '' ? $wEnd : null,
                ':supplier_name' => $supplier !== '' ? $supplier : null,
                ':notes' => $notes !== '' ? $notes : null,
            ]);
            $ok = 'Sold equipment added.';
        }
    }
}

$stmt = $pdo->prepare("SELECT * FROM project_sold_equipment WHERE project_id = :pid ORDER BY warranty_end ASC, id DESC");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="page-header">
  <div class="page-header-title">
    <h1>Sold Equipment</h1>
    <span><?php echo h(($project['code'] ?? '') . ' · ' . ($project['title'] ?? '') . ' · ' . ($project['customer_name'] ?? '')); ?></span>
  </div>
  <div class="page-header-actions"><a class="btn btn-secondary btn-sm" href="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">? ??s? st? ????</a></div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-success"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

    <div class="page-header-title"><h1 style="font-size:1.05rem">Add sold equipment</h1><span>Customer purchase + warranty period</span></div>
    <form method="post">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Item name</label><input type="text" name="item_name" placeholder="Pump / Filter / Heat Pump"></div>
        <div class="form-group"><label>Brand</label><input type="text" name="brand"></div>
        <div class="form-group"><label>Model</label><input type="text" name="model"></div>
        <div class="form-group"><label>Serial number</label><input type="text" name="serial_number"></div>
        <div class="form-group"><label>Purchase date</label><input type="date" name="purchase_date" value="<?php echo date('Y-m-d'); ?>"></div>
        <div class="form-group"><label>Warranty start</label><input type="date" name="warranty_start" value="<?php echo date('Y-m-d'); ?>"></div>
        <div class="form-group"><label>Warranty end</label><input type="date" name="warranty_end"></div>
        <div class="form-group"><label>Supplier</label><input type="text" name="supplier_name"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"></textarea></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Save equipment</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Warranty list</h1><span>Equipment sold inside this project</span></div>
    <?php if (!$rows): ?>
      <p class="small">No sold equipment yet.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Item</th><th>Serial</th><th>Warranty end</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?php echo h(trim(($r['item_name'] ?? '') . ' ' . ($r['brand'] ?? '') . ' ' . ($r['model'] ?? ''))); ?></td>
                <td><?php echo h($r['serial_number']); ?></td>
                <td><?php echo h($r['warranty_end']); ?></td>
                <td>
                  <form method="post" onsubmit="return confirm('Delete equipment record?')">
      <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                    <input type="hidden" name="row_id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-outline-light" type="submit">Delete</button>
                  </form>
                </td>
              </tr>
              <tr>
                <td colspan="4" class="small">
                  Purchase: <?php echo h($r['purchase_date']); ?>
                  <?php if (!empty($r['warranty_start'])) echo ' · Warranty start: ' . h($r['warranty_start']); ?>
                  <?php if (!empty($r['supplier_name'])) echo ' · Supplier: ' . h($r['supplier_name']); ?>
                  <?php if (!empty($r['notes'])) echo ' · ' . h($r['notes']); ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

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