<?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 if (!empty($r['description'])): ?>
                <div><strong>Περιγραφή:</strong> <?php echo h((string)$r['description']); ?></div>
              <?php endif; ?>
              <?php if (!empty($r['notes'])): ?>
                <div><strong>Σημειώσεις:</strong> <?php echo h((string)$r['notes']); ?></div>
              <?php endif; ?>
              <?php if ($canViewCostings && !empty($r['partner_quote_notes'])): ?>
                <div><strong>Partner costing notes:</strong> <?php echo h((string)$r['partner_quote_notes']); ?></div>
              <?php endif; ?>
              
              <?php
                // Fetch assignments and photos for this partner on this project
                $stmtAss = $pdo->prepare("SELECT id, offer_filename, status FROM project_assignments WHERE project_id = ? AND external_partner_id = ?");
                $stmtAss->execute([$projectId, $r['external_partner_id']]);
                $partnerAssignments = $stmtAss->fetchAll(PDO::FETCH_ASSOC);
              ?>
              <?php if ($partnerAssignments): ?>
                <div style="margin-top:6px; display:flex; flex-direction:column; gap:6px;">
                  <?php foreach ($partnerAssignments as $pa): ?>
                    <?php if (!empty($pa['offer_filename'])): 
                      $filePath = __DIR__ . '/../uploads/project_offers/' . $pa['offer_filename'];
                      $fileExists = file_exists($filePath);
                    ?>
                      <div style="margin-top:2px;">
                        <strong>📄 Προσφορά (Assignment #<?php echo $pa['id']; ?>):</strong> 
                        <?php if ($fileExists): ?>
                          <a href="/gopools/public/uploads/project_offers/<?php echo h($pa['offer_filename']); ?>" target="_blank" style="color:var(--gp-primary);font-weight:700;">Download Offer Document</a>
                        <?php else: ?>
                          <span style="color:var(--gp-muted);font-style:italic;">Δεν βρέθηκε το αρχείο στο διακομιστή (<?php echo h($pa['offer_filename']); ?>)</span>
                        <?php endif; ?>
                      </div>
                    <?php endif; ?>
                    
                    <?php
                      // Fetch photos associated with this assignment
                      $stmtPics = $pdo->prepare("SELECT filename, category FROM project_photos WHERE assignment_id = ?");
                      $stmtPics->execute([$pa['id']]);
                      $partnerPics = $stmtPics->fetchAll(PDO::FETCH_ASSOC);
                    ?>
                    <?php if ($partnerPics): ?>
                      <div style="margin-top:4px; display:flex; flex-wrap:wrap; gap:8px;">
                        <?php foreach ($partnerPics as $pPic): ?>
                          <div style="position:relative; display:inline-block; border:1px solid var(--gp-card-border); border-radius:6px; overflow:hidden;">
                            <a href="<?php echo gp_upload_url('project_photos', $pPic['filename']); ?>" target="_blank">
                              <img src="<?php echo gp_upload_url('project_photos', $pPic['filename']); ?>" style="width:70px; height:50px; object-fit:cover; display:block;" onerror="this.src='/gopools/public/uploads/project_photos/<?php echo h($pPic['filename']); ?>'">
                            </a>
                            <span style="position:absolute; bottom:0; left:0; right:0; background:rgba(0,0,0,0.65); color:#fff; font-size:0.5rem; text-align:center; padding:1px 0; font-weight:700;">
                              <?php echo $pPic['category'] === 'pool' ? 'Πισίνα' : 'Μηχ/σιο'; ?>
                            </span>
                          </div>
                        <?php endforeach; ?>
                      </div>
                    <?php endif; ?>
                  <?php endforeach; ?>
                </div>
              <?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'; ?>
