<?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);

// Check if user can view costings
$canViewCostings = function_exists('gp_user_perm') ? gp_user_perm($pdo, 'perm_costings') : gp_is_admin_like();

$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') {
    gp_require_csrf();
    $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: /gopools/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: /gopools/public/projects/partners.php?project_id=' . $projectId);
        exit;
    }
}

$stmt = $pdo->prepare("
    SELECT
        pp.*,
        pp.paid_date,
        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';
?>
<?php if (function_exists('gp_render_project_menu')) gp_render_project_menu($pdo, $projectId); ?>

<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="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">Back to project</a>
  </div>
</div>

<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 if ($canViewCostings): ?>€ <?php echo h(number_format($totalAgreed, 2)); ?><?php else: ?>🔒 Κρυπτό<?php endif; ?></div></div>
  <div class="card"><div class="small">External paid</div><div style="font-size:1.4rem;font-weight:700"><?php if ($canViewCostings): ?>€ <?php echo h(number_format($totalPaid, 2)); ?><?php else: ?>🔒 Κρυπτό<?php endif; ?></div></div>
  <div class="card"><div class="small">External balance</div><div style="font-size:1.4rem;font-weight:700"><?php if ($canViewCostings): ?>€ <?php echo h(number_format($balance, 2)); ?><?php else: ?>🔒 Κρυπτό<?php endif; ?></div></div>
  <div class="card"><div class="small">Partner quoted total</div><div style="font-size:1.4rem;font-weight:700"><?php if ($canViewCostings): ?>€ <?php echo h(number_format($totalPartnerQuoted, 2)); ?><?php else: ?>🔒 Κρυπτό<?php endif; ?></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">
      <?php echo csrf_field(); ?>
      <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="/gopools/public/partners/index.php">Open partners</a>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Λίστα Συνεργατών</h1></div>
    <div class="table-responsive">
      <table class="table">
        <thead>
        <tr>
            <th>Partner</th>
            <th>Specialty</th>
            <th>Ημ. Εργασίας</th>
            <?php if ($canViewCostings): ?>
            <th>Συμφωνηθέν</th>
            <th>Πληρωθέν</th>
            <th>Partner quote</th>
            <th>Quote status</th>
            <?php endif; ?>
            <th>Εξόφληση</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r):
            $isPaid = ($r['status'] === 'paid');
            $paidDate = $r['paid_date'] ?? null;
          ?>
          <tr id="pp-row-<?php echo (int)$r['id']; ?>">
            <td>
              <div style="font-weight:700;font-size:.88rem;"><?php echo h(($r['company_name'] ?? '')); ?></div>
              <div style="font-size:.72rem;color:var(--gp-muted);"><?php echo h($r['contact_person'] ?? ''); ?></div>
            </td>
            <td style="font-size:.85rem;"><?php echo h($r['specialty'] ?? ''); ?></td>
            <td style="font-size:.85rem;"><?php echo $r['work_date'] ? gp_date($r['work_date']) : '—'; ?></td>
            <?php if ($canViewCostings): ?>
            <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 style="font-size:.8rem;">
              <?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>
            <?php endif; ?>

            <!-- ── Εξόφληση column ── -->
            <td style="min-width:180px;">
              <?php if ($isPaid): ?>
                <!-- Already paid -->
                <div id="paid-badge-<?php echo (int)$r['id']; ?>" style="display:flex;flex-direction:column;gap:4px;">
                  <span style="background:rgba(16,185,129,.12);color:#10b981;border:1px solid rgba(16,185,129,.3);border-radius:20px;padding:3px 10px;font-size:.75rem;font-weight:700;display:inline-flex;align-items:center;gap:5px;">
                    ✅ Εξοφλήθηκε<?php if ($paidDate): ?> · <?php echo gp_date($paidDate); ?><?php endif; ?>
                  </span>
                  <button onclick="unpayPartner(<?php echo (int)$r['id']; ?>)" class="btn btn-sm btn-outline-light" style="font-size:.7rem;padding:2px 8px;color:#f59e0b;border-color:rgba(245,158,11,.3);">↩ Αναίρεση</button>
                </div>
              <?php else: ?>
                <!-- Not paid yet -->
                <div id="paid-badge-<?php echo (int)$r['id']; ?>" style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
                  <input type="date" id="pay-date-<?php echo (int)$r['id']; ?>" value="<?php echo date('Y-m-d'); ?>"
                    style="padding:4px 8px;border-radius:8px;border:1px solid var(--gp-card-border);background:var(--gp-card-bg);color:var(--gp-text);font-size:.78rem;">
                  <button onclick="payPartner(<?php echo (int)$r['id']; ?>)" class="btn btn-sm btn-primary" style="font-size:.75rem;padding:4px 10px;">💰 Εξόφληση</button>
                </div>
              <?php endif; ?>
            </td>

            <td>
              <form method="post" onsubmit="return confirm('Διαγραφή συνεργάτη από αυτό το έργο;')">
      <?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="link_id" value="<?php echo (int)$r['id']; ?>">
                <button class="btn btn-sm btn-outline-light" type="submit" style="color:#ef4444;border-color:rgba(239,68,68,.2);">🗑</button>
              </form>
            </td>
          </tr>
          <tr>
            <td colspan="<?php echo $canViewCostings ? 9 : 5; ?>" class="small" style="color:var(--gp-muted);padding-top:2px;padding-bottom:10px;">
              <?php echo h((string)($r['description'] ?? '')); ?>
              <?php if (!empty($r['notes'])): ?> · <?php echo h((string)$r['notes']); ?><?php endif; ?>
              <?php if ($canViewCostings && !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>

<script>
function payPartner(id) {
  const dateVal = document.getElementById('pay-date-' + id)?.value || '';
  const fd = new FormData();
  fd.append('id', id);
  fd.append('action', 'pay');
  fd.append('paid_date', dateVal);
  fetch('/gopools/public/api/partner_mark_paid.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(res => {
      if (res.ok) {
        const badge = document.getElementById('paid-badge-' + id);
        const dateLabel = res.paid_date ? ' · ' + formatDate(res.paid_date) : '';
        badge.innerHTML = `
          <span style="background:rgba(16,185,129,.12);color:#10b981;border:1px solid rgba(16,185,129,.3);border-radius:20px;padding:3px 10px;font-size:.75rem;font-weight:700;display:inline-flex;align-items:center;gap:5px;">
            ✅ Εξοφλήθηκε${dateLabel}
          </span>
          <button onclick="unpayPartner(${id})" class="btn btn-sm btn-outline-light" style="font-size:.7rem;padding:2px 8px;color:#f59e0b;border-color:rgba(245,158,11,.3);">↩ Αναίρεση</button>`;
      } else {
        alert('Σφάλμα: ' + (res.error || 'Unknown'));
      }
    }).catch(() => alert('Network error'));
}

function unpayPartner(id) {
  if (!confirm('Αναίρεση εξόφλησης;')) return;
  const fd = new FormData();
  fd.append('id', id);
  fd.append('action', 'unpay');
  fetch('/gopools/public/api/partner_mark_paid.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(res => {
      if (res.ok) {
        const badge = document.getElementById('paid-badge-' + id);
        const today = new Date().toISOString().split('T')[0];
        badge.innerHTML = `
          <input type="date" id="pay-date-${id}" value="${today}"
            style="padding:4px 8px;border-radius:8px;border:1px solid var(--gp-card-border);background:var(--gp-card-bg);color:var(--gp-text);font-size:.78rem;">
          <button onclick="payPartner(${id})" class="btn btn-sm btn-primary" style="font-size:.75rem;padding:4px 10px;">💰 Εξόφληση</button>`;
      }
    }).catch(() => alert('Network error'));
}

function formatDate(s) {
  if (!s) return '';
  const [y, m, d] = s.split('-');
  return d + '/' + m + '/' + y;
}
</script>

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