<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
auth_require_customer_portal();
$pdo = crm_pdo();
$page_title = 'Customer Portal';

$customerId = auth_customer_id();

if (auth_is_admin_like() && $customerId <= 0) {
    $customers = $pdo->query("SELECT id, name, email FROM customers WHERE active = 1 ORDER BY name ASC")->fetchAll();
    include __DIR__ . '/../includes/header.php';
    ?>
    <div class="page-header">
      <div class="page-header-title">
        <h1>Customer Portal</h1>
        <span>Admin access — choose customer</span>
      </div>
    </div>
    <div class="card">
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Customer</th><th>Email</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($customers as $c): ?>
              <tr>
                <td><?php echo h($c['name']); ?></td>
                <td><?php echo h($c['email']); ?></td>
                <td><a class="btn btn-sm btn-outline-light" href="/gopools/public/customers/my_warranties.php?customer_id=<?php echo (int)$c['id']; ?>">?????�a Portal</a></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

if ($customerId <= 0) {
    http_response_code(403);
    exit('Customer record not linked.');
}

$stmt = $pdo->prepare("
    SELECT pse.*, p.title AS project_title, p.code AS project_code
    FROM project_sold_equipment pse
    LEFT JOIN projects p ON p.id = pse.project_id
    WHERE pse.customer_id = :customer_id
    ORDER BY COALESCE(pse.warranty_end, '9999-12-31') ASC, pse.id DESC
");
$stmt->execute([':customer_id' => $customerId]);
$rows = $stmt->fetchAll();

$projectsStmt = $pdo->prepare("SELECT id, code, title, status FROM projects WHERE customer_id = :cid ORDER BY id DESC");
$projectsStmt->execute([':cid' => $customerId]);
$myProjects = $projectsStmt->fetchAll();

// Fetch their uploaded photos
$myPhotos = [];
if ($myProjects) {
    $pids = array_column($myProjects, 'id');
    $in = implode(',', array_fill(0, count($pids), '?'));
    $photoStmt = $pdo->prepare("SELECT pp.*, p.title AS project_title FROM project_photos pp JOIN projects p ON p.id = pp.project_id WHERE pp.project_id IN ($in) AND pp.uploaded_by_type = 'customer' ORDER BY pp.id DESC");
    $photoStmt->execute($pids);
    $myPhotos = $photoStmt->fetchAll();
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Customer Portal</h1>
    <span><?php echo auth_is_admin_like() ? 'Admin view' : 'My Projects & Warranties'; ?></span>
  </div>
</div>

<div class="card">
  <?php if (!$rows): ?>
    <p class="small">No warranty records available.</p>
  <?php else: ?>
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>Project</th>
            <th>Equipment</th>
            <th>Serial</th>
            <th>Purchase</th>
            <th>Warranty start</th>
            <th>Warranty end</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
            <?php $expired = !empty($r['warranty_end']) && strtotime((string)$r['warranty_end']) < strtotime(date('Y-m-d')); ?>
            <tr>
              <td><?php echo h(($r['project_code'] ?? '') . ' · ' . ($r['project_title'] ?? '')); ?></td>
              <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['purchase_date']); ?></td>
              <td><?php echo h($r['warranty_start']); ?></td>
              <td><?php echo h($r['warranty_end']); ?></td>
              <td><?php echo $expired ? 'Expired' : 'Active'; ?></td>
            </tr>
            <tr><td colspan="7" class="small"><?php echo h(trim(('Supplier: ' . ($r['supplier_name'] ?? '')) . (!empty($r['notes']) ? ' · ' . $r['notes'] : ''))); ?></td></tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>

<div class="grid-2">
  <!-- Upload Form -->
  <div class="card">
    <div class="page-header-title" style="margin-bottom:1rem">
      <h1 style="font-size:1.1rem">Upload Project Photo</h1>
      <span>Send photos of before/after or report issues</span>
    </div>
    
    <?php if (!$myProjects): ?>
      <p class="small text-danger">No active projects found to attach photos to.</p>
    <?php else: ?>
      <form id="customerPhotoForm" style="display:flex; flex-direction:column; gap:1rem;">
        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
        
        <div class="form-group">
          <label>Select Project</label>
          <select name="project_id" class="form-control" required>
            <option value="">Select project...</option>
            <?php foreach ($myProjects as $p): ?>
              <option value="<?php echo (int)$p['id']; ?>"><?php echo h($p['code'] . ' - ' . $p['title']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label>Category</label>
          <select name="category" class="form-control" required>
            <option value="Στάδιο πριν την ολοκλήρωση (Before Completion)">Στάδιο πριν την ολοκλήρωση (Before Completion)</option>
            <option value="Πρόβλημα μετά την ολοκλήρωση (Issue After Completion)">Πρόβλημα μετά την ολοκλήρωση (Issue After Completion)</option>
            <option value="Άλλο (Other)">Άλλο (Other)</option>
          </select>
        </div>

        <div class="form-group">
          <label>Photo Title / Notes</label>
          <input type="text" name="title" class="form-control" placeholder="Optional brief description..." maxlength="250">
        </div>

        <div class="form-group">
          <label>Upload Images (μπορείτε να επιλέξετε πολλές)</label>
          <input type="file" name="photo" accept="image/jpeg, image/png, image/webp" class="form-control" multiple required>
        </div>

        <div id="uploadFeedback" class="alert" style="display:none; padding:.5rem; margin-top:.5rem; border-radius:6px;"></div>

        <div class="form-actions">
          <button type="submit" class="btn btn-primary" id="uploadBtn">Upload Photo</button>
        </div>
      </form>
    <?php endif; ?>
  </div>

  <!-- Uploaded Photos Display -->
  <div class="card">
    <div class="page-header-title" style="margin-bottom:1rem">
      <h1 style="font-size:1.1rem">My Uploaded Photos</h1>
      <span>Gallery of photos you have sent us</span>
    </div>
    <?php if (!$myPhotos): ?>
      <p class="small">?e? ?p?????? f?t???af?e? a??�a.</p>
    <?php else: ?>
      <div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap:1rem;">
        <?php foreach ($myPhotos as $ph): ?>
          <div style="border:1px solid var(--gp-card-border); border-radius:8px; overflow:hidden; background:var(--gp-nav-bg-2);">
             <a href="/gopools/public/uploads/photos/<?php echo h($ph['filename']); ?>" target="_blank">
               <img src="/gopools/public/uploads/photos/<?php echo h($ph['filename']); ?>" style="width:100%; height:110px; object-fit:cover; display:block;">
             </a>
             <div style="padding:.5rem;">
               <div style="font-size:.75rem; font-weight:700; color:var(--gp-primary); margin-bottom:.25rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;" title="<?php echo h($ph['category']); ?>">
                 <?php echo h($ph['category']); ?>
               </div>
               <div style="font-size:.7rem; color:var(--gp-muted); line-height:1.3; margin-bottom:.25rem;">
                 <?php echo h($ph['title'] ?? 'No title'); ?>
               </div>
               <div style="font-size:.65rem; color:var(--gp-text); opacity:0.6;">
                 <?php echo h(gp_date((string)$ph['created_at'])); ?>
               </div>
               <div style="font-size:.65rem; color:var(--gp-text); opacity:0.8; margin-top:.15rem; font-weight:600;">
                 <?php echo $ph['shared_with_crew'] ? '<span style="color:#16a34a;">Shared with crew</span>' : 'Received'; ?>
               </div>
             </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  var form = document.getElementById('customerPhotoForm');
  if (form) {
    form.addEventListener('submit', async function(e){
      e.preventDefault();
      var btn = document.getElementById('uploadBtn');
      var fb = document.getElementById('uploadFeedback');
      var fileInput = form.querySelector('input[type=file]');
      var files = fileInput.files;
      if (!files || files.length === 0) return;
      var projectId = form.querySelector('select[name=project_id]').value;
      var category = form.querySelector('select[name=category]').value;
      var title = form.querySelector('input[name=title]').value;
      var csrfToken = form.querySelector('input[name=csrf_token]').value;

      btn.disabled = true;
      btn.textContent = 'Uploading...';
      fb.style.display = 'block';
      fb.style.background = '#e0f2fe'; fb.style.color = '#0369a1';

      var successCount = 0; var failCount = 0;
      for (var i = 0; i < files.length; i++) {
        fb.textContent = 'Ανέβασμα ' + (i + 1) + ' από ' + files.length + '...';
        var fd = new FormData();
        fd.append('photo', files[i]);
        fd.append('project_id', projectId);
        fd.append('category', category);
        fd.append('title', title);
        fd.append('csrf_token', csrfToken);
        try {
          var res = await fetch('/gopools/public/api/customer_upload_photo.php', { method: 'POST', body: fd }).then(r => r.json());
          if (res.ok) successCount++;
          else { failCount++; fb.textContent = res.error || 'Server error'; fb.style.background = '#fee2e2'; fb.style.color = '#991b1b'; }
        } catch(err) { failCount++; }
      }
      if (failCount === 0) {
        fb.textContent = '✅ ' + successCount + ' φωτογραφίες ανέβηκαν επιτυχώς!';
        fb.style.background = '#dcfce7'; fb.style.color = '#166534';
        setTimeout(function() { window.location.reload(); }, 1500);
      } else if (successCount > 0) {
        fb.textContent = '⚠️ ' + successCount + ' επιτυχία, ' + failCount + ' αποτυχία.';
        fb.style.background = '#fef9c3'; fb.style.color = '#854d0e';
        btn.disabled = false; btn.textContent = 'Upload Photo';
      } else {
        btn.disabled = false; btn.textContent = 'Upload Photo';
      }
    });
  }
});
</script>

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