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

$pdo = crm_pdo();
$page_title = 'Project partners';

$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
if (function_exists('gp_require_project_edit')) 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.');

$partners = $pdo->query("
    SELECT id, company_name, contact_person, specialty
    FROM external_partners
    WHERE active = 1
    ORDER BY company_name ASC
")->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));

    if ($action === 'delete') {
        $linkId = (int)($_POST['link_id'] ?? 0);
        $stmt = $pdo->prepare("DELETE FROM project_partners WHERE id = :id AND project_id = :pid");
        $stmt->execute([':id' => $linkId, ':pid' => $projectId]);
        header('Location: /public/projects/partners.php?project_id=' . $projectId);
        exit;
    }

    $externalPartnerId = (int)($_POST['external_partner_id'] ?? 0);
    $workDate = trim((string)($_POST['work_date'] ?? ''));
    $description = trim((string)($_POST['description'] ?? ''));
    $agreedCost = trim((string)($_POST['agreed_cost'] ?? ''));
    $paidAmount = trim((string)($_POST['paid_amount'] ?? ''));
    $status = trim((string)($_POST['status'] ?? 'planned'));
    $notes = trim((string)($_POST['notes'] ?? ''));

    if ($externalPartnerId <= 0) $errors[] = 'Partner is required.';

    if (!$errors) {
        $stmt = $pdo->prepare("
            INSERT INTO project_partners
                (project_id, external_partner_id, work_date, description, agreed_cost, paid_amount, status, notes)
            VALUES
                (:project_id, :external_partner_id, :work_date, :description, :agreed_cost, :paid_amount, :status, :notes)
        ");
        $stmt->execute([
            ':project_id' => $projectId,
            ':external_partner_id' => $externalPartnerId,
            ':work_date' => $workDate !== '' ? $workDate : null,
            ':description' => $description !== '' ? $description : null,
            ':agreed_cost' => $agreedCost !== '' ? $agreedCost : null,
            ':paid_amount' => $paidAmount !== '' ? $paidAmount : null,
            ':status' => $status !== '' ? $status : 'planned',
            ':notes' => $notes !== '' ? $notes : null,
        ]);
        header('Location: /public/projects/partners.php?project_id=' . $projectId);
        exit;
    }
}

$stmt = $pdo->prepare("
    SELECT
        pp.*,
        ep.company_name,
        ep.contact_person,
        ep.specialty,
        ppc.quote_amount AS partner_quote_amount,
        ppc.status AS partner_quote_status,
        ppc.updated_at AS partner_quote_updated_at,
        ppc.notes AS partner_quote_notes
    FROM project_partners pp
    LEFT JOIN external_partners ep
        ON ep.id = pp.external_partner_id
    LEFT JOIN partner_project_costings ppc
        ON ppc.project_id = pp.project_id
       AND ppc.external_partner_id = pp.external_partner_id
    WHERE pp.project_id = :pid
    ORDER BY pp.work_date DESC, pp.id DESC
");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

$totalAgreed = 0.0;
$totalPaid = 0.0;
foreach ($rows as $r) {
    $totalAgreed += (float)($r['agreed_cost'] ?? 0);
    $totalPaid += (float)($r['paid_amount'] ?? 0);
}
$balance = $totalAgreed - $totalPaid;

$totalPartnerQuoted = 0.0;
try {
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(quote_amount),0) FROM partner_project_costings WHERE project_id = :pid");
    $stmt->execute([':pid' => $projectId]);
    $totalPartnerQuoted = (float)$stmt->fetchColumn();
} catch (Throwable $e) {
    $totalPartnerQuoted = 0.0;
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Project partners</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="/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">Back to project</a>
  </div>
</div>

<?php if (function_exists('gp_render_project_menu')) gp_render_project_menu($pdo, $projectId); ?>

<div class="grid-4" style="margin-bottom:14px">
  <div class="card"><div class="small">External agreed</div><div style="font-size:1.4rem;font-weight:700">€ <?php echo h(number_format($totalAgreed, 2)); ?></div></div>
  <div class="card"><div class="small">External paid</div><div style="font-size:1.4rem;font-weight:700">€ <?php echo h(number_format($totalPaid, 2)); ?></div></div>
  <div class="card"><div class="small">External balance</div><div style="font-size:1.4rem;font-weight:700">€ <?php echo h(number_format($balance, 2)); ?></div></div>
  <div class="card"><div class="small">Partner quoted total</div><div style="font-size:1.4rem;font-weight:700">€ <?php echo h(number_format($totalPartnerQuoted, 2)); ?></div></div>
</div>

<div class="grid-2">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Add external partner to project</h1></div>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group">
          <label>Partner</label>
          <select name="external_partner_id">
            <option value="0">Select...</option>
            <?php foreach ($partners as $p): ?>
              <option value="<?php echo (int)$p['id']; ?>"><?php echo h(($p['company_name'] ?? '') . ' · ' . ($p['contact_person'] ?? '') . ' · ' . ($p['specialty'] ?? '')); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group"><label>Work date</label><input type="date" name="work_date" value="<?php echo date('Y-m-d'); ?>"></div>
        <div class="form-group"><label>Description</label><input type="text" name="description" placeholder="Electrical work / Excavation"></div>
        <div class="form-group"><label>Agreed cost</label><input type="number" step="0.01" name="agreed_cost"></div>
        <div class="form-group"><label>Paid amount</label><input type="number" step="0.01" name="paid_amount"></div>
        <div class="form-group">
          <label>Status</label>
          <select name="status">
            <?php foreach (['planned','working','done','paid','cancelled'] as $s): ?>
              <option value="<?php echo h($s); ?>"><?php echo h($s); ?></option>
            <?php endforeach; ?>
          </select>
        </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 partner link</button>
        <a class="btn btn-secondary" href="/public/partners/index.php">Open partners</a>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Current partner list</h1></div>
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>Partner</th>
            <th>Specialty</th>
            <th>Date</th>
            <th>Agreed</th>
            <th>Paid</th>
            <th>Partner quote</th>
            <th>Quote status</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?php echo h(($r['company_name'] ?? '') . ' · ' . ($r['contact_person'] ?? '')); ?></td>
            <td><?php echo h($r['specialty'] ?? ''); ?></td>
            <td><?php echo h($r['work_date'] ?? ''); ?></td>
            <td>€ <?php echo h(number_format((float)($r['agreed_cost'] ?? 0), 2)); ?></td>
            <td>€ <?php echo h(number_format((float)($r['paid_amount'] ?? 0), 2)); ?></td>
            <td>
              <?php if ($r['partner_quote_amount'] !== null): ?>
                € <?php echo h(number_format((float)$r['partner_quote_amount'], 2)); ?>
              <?php else: ?>
                -
              <?php endif; ?>
            </td>
            <td>
              <?php if ($r['partner_quote_amount'] !== null): ?>
                <?php echo h((string)($r['partner_quote_status'] ?? 'submitted')); ?>
                <?php if (!empty($r['partner_quote_updated_at'])): ?>
                  <div class="small"><?php echo h((string)$r['partner_quote_updated_at']); ?></div>
                <?php endif; ?>
              <?php else: ?>
                -
              <?php endif; ?>
            </td>
            <td>
              <form method="post" onsubmit="return confirm('Delete project partner link?')">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                <input type="hidden" name="link_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="8" class="small">
              <?php echo h((string)($r['description'] ?? '')); ?>
              <?php if (!empty($r['notes'])): ?> · <?php echo h((string)$r['notes']); ?><?php endif; ?>
              <?php if (!empty($r['partner_quote_notes'])): ?> · Partner costing notes: <?php echo h((string)$r['partner_quote_notes']); ?><?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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