<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-competitor_analysis">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Competitor Analysis</h4>
      <button id="ca_btnNewCompany" class="btn btn-primary">Add Competitor</button>
    </div>

    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <div class="row g-2 align-items-end">
          <div class="col-md-4">
            <label class="form-label">Search</label>
            <div class="input-group">
              <input type="text" id="ca_q" class="form-control" placeholder="Company / Contact / Phone">
              <button class="btn btn-outline-secondary" id="ca_btnSearch"><i class="bi bi-search"></i></button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm mt-4 mb-3">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <div>
            <h6 class="mb-0">Competitor Report</h6>
            <small class="text-muted">Select month and optionally filter by Color/Finish, then generate printable report.</small>
          </div>
          <div class="d-flex flex-wrap gap-2 align-items-end">
            <div>
              <label class="form-label mb-1">Month</label>
              <input type="month" id="ca_reportMonth" class="form-control form-control-sm">
            </div>
            <div>
              <label class="form-label mb-1">Color</label>
              <select id="ca_reportColor" class="form-select form-select-sm"></select>
            </div>
            <div>
              <label class="form-label mb-1">Finish</label>
              <select id="ca_reportFinish" class="form-select form-select-sm"></select>
            </div>
            <button class="btn btn-outline-secondary btn-sm" id="ca_btnLoadReport">Get Report</button>
            <button class="btn btn-outline-primary btn-sm" id="ca_btnPrintReport">Print</button>
          </div>
        </div>
        <div id="ca_reportContainer" class="table-responsive small border rounded p-2" style="max-height: 400px; overflow:auto;">
          <div class="text-muted">Select a month and click \"Get Report\".</div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <div>
            <h6 class="mb-0">Yearly Price Chart</h6>
            <small class="text-muted">Select a finish and view average price per SQF by month for its colors.</small>
          </div>
          <div class="d-flex flex-wrap gap-2 align-items-end">
            <div>
              <label class="form-label mb-1">Year</label>
              <input type="number" id="ca_chartYear" class="form-control form-control-sm" min="2000" max="2100">
            </div>
            <div>
              <label class="form-label mb-1">Finish</label>
              <select id="ca_chartFinish" class="form-select form-select-sm"></select>
            </div>
            <button class="btn btn-outline-secondary btn-sm" id="ca_btnLoadChart">Load Chart</button>
          </div>
        </div>
        <div style="height:320px;">
          <canvas id="ca_priceChart"></canvas>
        </div>
      </div>
    </div>

    <div class="row g-3">
      <div class="col-lg-5">
        <div class="card shadow-sm h-100">
          <div class="card-body">
            <h6 class="mb-3">Competitors</h6>
            <div class="table-responsive" style="max-height: 420px; overflow:auto;">
              <table class="table table-hover align-middle" id="ca_tblCompanies">
                <thead>
                  <tr>
                    <th>Company</th>
                    <th>Contact</th>
                    <th>Phone</th>
                    <th style="width:110px">Actions</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <div class="col-lg-7">
        <div class="card shadow-sm h-100">
          <div class="card-body d-flex flex-column">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div>
                <h6 class="mb-0">Items / Monthly Pricing</h6>
                <small class="text-muted" id="ca_selCompanyLabel">Select a competitor to manage items.</small>
              </div>
              <button id="ca_btnNewItem" class="btn btn-outline-primary btn-sm" disabled>Add Item</button>
            </div>

            <div class="border rounded p-2 mb-2 bg-light small">
              <div class="row g-2 align-items-end">
                <div class="col-md-4">
                  <label class="form-label">Month / Year</label>
                  <input type="month" id="ca_filterDate" class="form-control">
                </div>
                <div class="col-md-3">
                  <label class="form-label">Color</label>
                  <select id="ca_filterColor" class="form-select"></select>
                </div>
                <div class="col-md-3">
                  <label class="form-label">Finish</label>
                  <select id="ca_filterFinish" class="form-select"></select>
                </div>
                <div class="col-md-2">
                  <button class="btn btn-outline-secondary w-100" id="ca_btnItemFilter"><i class="bi bi-funnel"></i></button>
                </div>
              </div>
            </div>

            <div class="table-responsive flex-grow-1">
              <table class="table table-sm align-middle" id="ca_tblItems">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Color</th>
                    <th>Finish</th>
                    <th>Price / SQF</th>
                    <th>Remarks</th>
                    <th style="width:90px">Actions</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <input type="hidden" id="ca_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />
  </div>
</div>

<!-- Company Modal -->
<div class="modal fade" id="ca_companyModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Competitor</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="ca_companyForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" id="ca_companyCsrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="ca_companyId">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Company Name<span class="text-danger">*</span></label>
              <input type="text" class="form-control" name="company_name" id="ca_companyName" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Contact Person</label>
              <input type="text" class="form-control" name="contact_person" id="ca_contactPerson">
            </div>
            <div class="col-md-6">
              <label class="form-label">Contact Number</label>
              <input type="text" class="form-control" name="contact_number" id="ca_contactNumber">
            </div>
            <div class="col-md-6">
              <label class="form-label">Date of Analysis (default for new items)</label>
              <input type="date" class="form-control" id="ca_defaultDate">
            </div>
            <div class="col-12">
              <label class="form-label">Address</label>
              <input type="text" class="form-control" name="address" id="ca_address">
            </div>
            <div class="col-12">
              <label class="form-label">Remarks</label>
              <textarea class="form-control" name="remarks" id="ca_companyRemarks" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Item Modal -->
<div class="modal fade" id="ca_itemModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title">Competitor Item</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="ca_itemForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" id="ca_itemCsrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="ca_itemId">
          <input type="hidden" name="company_id" id="ca_itemCompanyId">
          <div class="mb-2">
            <label class="form-label">Date of Analysis</label>
            <input type="date" class="form-control" name="analysis_date" id="ca_itemDate">
          </div>
          <div class="mb-2">
            <label class="form-label">Color<span class="text-danger">*</span></label>
            <select class="form-select" name="color_id" id="ca_itemColor" required></select>
          </div>
          <div class="mb-2">
            <label class="form-label">Finish<span class="text-danger">*</span></label>
            <select class="form-select" name="finish_id" id="ca_itemFinish" required></select>
          </div>
          <div class="mb-2">
            <label class="form-label">Price per SQF</label>
            <input type="number" step="0.001" class="form-control" name="price_per_sqf" id="ca_itemPrice">
          </div>
          <div class="mb-2">
            <label class="form-label">Remarks</label>
            <textarea class="form-control" name="remarks" id="ca_itemRemarks" rows="2"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
(function(){
  if (!$('.page-competitor_analysis').length) return;
  const $tblCompanies = $('#ca_tblCompanies tbody');
  const $tblItems = $('#ca_tblItems tbody');
  const $csrf = $('#ca_csrf');
  let currentCompanyId = null;
  let defaultDate = null;
  let lastReportData = null;
  let COLORS = [];
  let FINISHES = [];
  let priceChart = null;

  function loadColorFinishOptions(cb){
    $.when(
      $.get('api/colors.php', { action:'list' }),
      $.get('api/finishes.php', { action:'list' })
    ).done(function(cRes, fRes){
      COLORS = (cRes[0].data||[]);
      FINISHES = (fRes[0].data||[]);
      const cOpts=['<option value="">All</option>'];
      const fOpts=['<option value="">All</option>'];
      COLORS.forEach(c=> cOpts.push(`<option value="${c.id}">${$('<div>').text(c.name||'').html()}</option>`));
      FINISHES.forEach(f=> fOpts.push(`<option value="${f.id}">${$('<div>').text(f.name||'').html()}</option>`));
      $('#ca_filterColor').html(cOpts.join(''));
      $('#ca_filterFinish').html(fOpts.join(''));
      // report filters use same options (All by default)
      $('#ca_reportColor').html(cOpts.join(''));
      $('#ca_reportFinish').html(fOpts.join(''));
      // yearly chart finish filter (All by default)
      $('#ca_chartFinish').html(fOpts.join(''));
      const cItemOpts=['<option value="">Select</option>'];
      const fItemOpts=['<option value="">Select</option>'];
      COLORS.forEach(c=> cItemOpts.push(`<option value="${c.id}">${$('<div>').text(c.name||'').html()}</option>`));
      FINISHES.forEach(f=> fItemOpts.push(`<option value="${f.id}">${$('<div>').text(f.name||'').html()}</option>`));
      $('#ca_itemColor').html(cItemOpts.join(''));
      $('#ca_itemFinish').html(fItemOpts.join(''));
      if (typeof cb === 'function') cb();
    }).fail(function(){
      alert('Failed to load colors/finishes');
    });
  }

  function loadYearlyChart(){
    const yearVal = $('#ca_chartYear').val();
    const year = parseInt(yearVal, 10);
    if (!year){
      alert('Please enter a valid year.');
      return;
    }
    const finish_id = $('#ca_chartFinish').val();
    if (!finish_id){
      alert('Please select a finish.');
      return;
    }
    $.get('api/competitor_analysis.php', { action:'yearly_chart', year, finish_id }, function(res){
      const rows = res.data || [];
      renderYearlyChart(rows, year, finish_id);
    }).fail(xhr=>{
      alert((xhr.responseJSON && xhr.responseJSON.message) || 'Failed to load chart data');
    });
  }

  function renderYearlyChart(rows, year, finish_id){
    const labels = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    const seriesMap = {};

    rows.forEach(r => {
      const m = parseInt(r.m,10);
      if (!m) return;
      const key = (r.color_name || 'No Color');
      if (!seriesMap[key]){
        seriesMap[key] = { label:key, data:new Array(12).fill(null) };
      }
      seriesMap[key].data[m-1] = r.avg_price != null ? Number(r.avg_price) : null;
    });

    const palette = ['#0d6efd','#198754','#dc3545','#fd7e14','#6f42c1','#20c997','#6610f2','#0dcaf0','#ffc107','#adb5bd'];
    const datasets = Object.keys(seriesMap).map((k, idx) => {
      const base = seriesMap[k];
      const color = palette[idx % palette.length];
      return {
        label: base.label,
        data: base.data,
        borderColor: color,
        backgroundColor: color,
        tension: 0.2,
        spanGaps: true
      };
    });

    const ctx = document.getElementById('ca_priceChart').getContext('2d');
    if (priceChart){ priceChart.destroy(); }
    priceChart = new Chart(ctx, {
      type: 'line',
      data: { labels, datasets },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          title: { display:true, text:'Average Price per SQF - ' + year },
          legend: { position:'bottom' }
        },
        scales: {
          y: {
            title: { display:true, text:'Price / SQF' },
            beginAtZero: true
          },
          x: {
            title: { display:true, text:'Month' }
          }
        }
      }
    });
  }

  function loadCompanies(selectedId){
    const q = $('#ca_q').val();
    $.get('api/competitor_analysis.php', { action:'list_companies', q }, function(res){
      const rows = res.data || [];
      $tblCompanies.empty();
      if (!rows.length){
        $tblCompanies.append('<tr><td colspan="4" class="text-center text-muted">No competitors</td></tr>');
        setCurrentCompany(null, '');
        return;
      }
      rows.forEach(r=>{
        const tr = $('<tr>').attr('data-id', r.id).attr('data-name', r.company_name||'');
        tr.append(`<td>${$('<div>').text(r.company_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.contact_person||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.contact_number||'').html()}</td>`);
        tr.append(`<td>
          <button class="btn btn-sm btn-outline-primary me-1 ca-edit" data-id="${r.id}"><i class="bi bi-pencil"></i></button>
          <button class="btn btn-sm btn-outline-danger ca-del" data-id="${r.id}"><i class="bi bi-trash"></i></button>
        </td>`);
        if (selectedId && String(selectedId) === String(r.id)) {
          tr.addClass('table-active');
        }
        $tblCompanies.append(tr);
      });

      if (selectedId){
        const $sel = $tblCompanies.find('tr[data-id="'+selectedId+'"]');
        if ($sel.length){
          setCurrentCompany(selectedId, $sel.data('name') || '');
          $tblCompanies.find('tr').not($sel).removeClass('table-active');
          $sel.addClass('table-active');
        }
      }
    });
  }

  function loadItems(){
    if (!currentCompanyId){
      $tblItems.empty();
      $tblItems.append('<tr><td colspan="5" class="text-center text-muted">Select a competitor</td></tr>');
      return;
    }
    const params = { action:'list_items', company_id: currentCompanyId };
    $.get('api/competitor_analysis.php', params, function(res){
      const rows = res.data || [];
      const filterYm = $('#ca_filterDate').val();
      const filterColor = $('#ca_filterColor').val();
      const filterFinish = $('#ca_filterFinish').val();
      $tblItems.empty();
      let filtered = rows;
      if (filterYm){
        filtered = filtered.filter(r => {
          const d = (r.analysis_date || '').slice(0, 7);
          return d === filterYm;
        });
      }
      if (filterColor){ filtered = filtered.filter(r=> String(r.color_id||'') === String(filterColor)); }
      if (filterFinish){ filtered = filtered.filter(r=> String(r.finish_id||'') === String(filterFinish)); }
      if (!filtered.length){
        $tblItems.append('<tr><td colspan="6" class="text-center text-muted">No items</td></tr>');
        return;
      }
      filtered.forEach(r=>{
        const tr = $('<tr>').attr('data-id', r.id);
        tr.append(`<td>${$('<div>').text(r.analysis_date||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.finish_name||'').html()}</td>`);
        tr.append(`<td>${r.price_per_sqf!=null ? Number(r.price_per_sqf).toFixed(3) : ''}</td>`);
        tr.append(`<td>${$('<div>').text(r.remarks||'').html()}</td>`);
        tr.append(`<td>
          <button class="btn btn-sm btn-outline-primary me-1 ca-item-edit" data-id="${r.id}"><i class="bi bi-pencil"></i></button>
          <button class="btn btn-sm btn-outline-danger ca-item-del" data-id="${r.id}"><i class="bi bi-trash"></i></button>
        </td>`);
        $tblItems.append(tr);
      });
    });
  }

  function setCurrentCompany(id, name){
    currentCompanyId = id;
    if (id){
      $('#ca_selCompanyLabel').text('Items for: ' + name);
      $('#ca_btnNewItem').prop('disabled', false);
    } else {
      $('#ca_selCompanyLabel').text('Select a competitor to manage items.');
      $('#ca_btnNewItem').prop('disabled', true);
    }
    loadItems();
  }

  function loadMonthlyReport(){
    const val = $('#ca_reportMonth').val();
    if (!val){
      alert('Please select a month.');
      return;
    }
    const [yearStr, monthStr] = val.split('-');
    const year = parseInt(yearStr,10), month=parseInt(monthStr,10);
    if (!year || !month){ alert('Invalid month'); return; }
    const color_id = $('#ca_reportColor').val();
    const finish_id = $('#ca_reportFinish').val();
    $('#ca_reportContainer').html('<div class="text-muted">Loading...</div>');
    $.get('api/competitor_analysis.php', { action:'monthly_report', year, month, color_id, finish_id }, function(res){
      const rows = res.data || [];
      lastReportData = rows;
      renderMonthlyReport(rows, year, month);
    }).fail(xhr=>{
      alert((xhr.responseJSON && xhr.responseJSON.message) || 'Failed to load report');
      $('#ca_reportContainer').html('<div class="text-danger">Failed to load report</div>');
    });
  }

  function renderMonthlyReport(rows, year, month){
    if (!rows.length){
      $('#ca_reportContainer').html('<div class="text-muted">No data for selected month.</div>');
      return;
    }
    const ym = (year+'-'+String(month).padStart(2,'0'));
    const $wrap = $('<div>');
    $wrap.append(`<h6 class="mb-2">Competitor Report - ${ym}</h6>`);
    const byCompany = {};
    rows.forEach(r=>{
      const cid = r.company_id;
      if (!byCompany[cid]) byCompany[cid] = { info:r, items:[] };
      if (r.item_id){ byCompany[cid].items.push(r); }
    });
    const $tbl = $('<table class="table table-sm table-bordered align-middle mb-0">');
    const $thead = $('<thead><tr><th>Company</th><th>Contact</th><th>Phone</th><th>Date</th><th>Color</th><th>Finish</th><th>Price / SQF</th><th>Remarks</th></tr></thead>');
    const $tbody = $('<tbody>');
    Object.keys(byCompany).forEach(cid=>{
      const g = byCompany[cid];
      const info = g.info;
      const items = g.items.length ? g.items : [null];
      items.forEach((it, idx)=>{
        const tr = $('<tr>');
        if (idx===0){
          tr.append(`<td rowspan="${items.length}"><strong>${$('<div>').text(info.company_name||'').html()}</strong><br><small>${$('<div>').text(info.address||'').html()}</small></td>`);
          tr.append(`<td rowspan="${items.length}">${$('<div>').text(info.contact_person||'').html()}</td>`);
          tr.append(`<td rowspan="${items.length}">${$('<div>').text(info.contact_number||'').html()}</td>`);
        }
        if (it){
          tr.append(`<td>${$('<div>').text(it.analysis_date||'').html()}</td>`);
          tr.append(`<td>${$('<div>').text(it.color_name||'').html()}</td>`);
          tr.append(`<td>${$('<div>').text(it.finish_name||'').html()}</td>`);
          tr.append(`<td>${it.price_per_sqf!=null ? Number(it.price_per_sqf).toFixed(3) : ''}</td>`);
          tr.append(`<td>${$('<div>').text(it.remarks||'').html()}</td>`);
        } else {
          tr.append('<td colspan="5" class="text-muted">No items for this month</td>');
        }
        $tbody.append(tr);
      });
    });
    $tbl.append($thead).append($tbody);
    $wrap.append($tbl);
    $('#ca_reportContainer').empty().append($wrap);
  }

  function printMonthlyReport(){
    if (!lastReportData || !lastReportData.length){
      alert('No report data to print. Please load a month first.');
      return;
    }
    const win = window.open('', '_blank');
    if (!win) return;
    const html = `<!DOCTYPE html><html><head><title>Competitor Report</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
      </head><body class="p-3">${$('#ca_reportContainer').html()}</body></html>`;
    win.document.open();
    win.document.write(html);
    win.document.close();
    win.focus();
    win.print();
  }

  // Company events
  $('#ca_btnSearch').on('click', function(){ loadCompanies(); });
  $('#ca_q').on('keydown', function(e){ if(e.key==='Enter'){ e.preventDefault(); loadCompanies(); }});

  $('#ca_btnNewCompany').on('click', function(){
    $('#ca_companyForm')[0].reset();
    $('#ca_companyId').val('');
    $('#ca_defaultDate').val(new Date().toISOString().slice(0,10));
    defaultDate = $('#ca_defaultDate').val();
    setCurrentCompany(null, '');
    $('#ca_companyModal').modal('show');
  });

  $tblCompanies.on('click', 'tr', function(e){
    // avoid row-click when clicking buttons
    if ($(e.target).closest('button').length) return;
    const id = $(this).data('id');
    const name = $(this).data('name') || '';
    $tblCompanies.find('tr').removeClass('table-active');
    $(this).addClass('table-active');
    setCurrentCompany(id, name);
  });

  $tblCompanies.on('click', '.ca-edit', function(e){
    e.stopPropagation();
    const id = $(this).data('id');
    $.get('api/competitor_analysis.php', { action:'get_company', id }, function(res){
      const d = res.data || {};
      $('#ca_companyId').val(d.id||'');
      $('#ca_companyName').val(d.company_name||'');
      $('#ca_contactPerson').val(d.contact_person||'');
      $('#ca_contactNumber').val(d.contact_number||'');
      $('#ca_address').val(d.address||'');
      $('#ca_companyRemarks').val(d.remarks||'');
      if (!$('#ca_defaultDate').val()) $('#ca_defaultDate').val(new Date().toISOString().slice(0,10));
      defaultDate = $('#ca_defaultDate').val();
      $('#ca_companyModal').modal('show');
    });
  });

  $tblCompanies.on('click', '.ca-del', function(e){
    e.stopPropagation();
    if (!confirm('Delete this competitor and its items?')) return;
    const id = $(this).data('id');
    const fd = new FormData();
    fd.append('csrf', $csrf.val());
    fd.append('action','delete_company');
    fd.append('id', id);
    $.ajax({ url:'api/competitor_analysis.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ if (currentCompanyId===id) setCurrentCompany(null, ''); loadCompanies(); })
      .fail(xhr=> alert((xhr.responseJSON && xhr.responseJSON.message) || 'Delete failed'));
  });

  $('#ca_companyForm').on('submit', function(e){
    e.preventDefault();
    const fd = new FormData(this);
    fd.append('action','save_company');
    $.ajax({ url:'api/competitor_analysis.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(res){
        $('#ca_companyModal').modal('hide');
        const newId = res && res.id ? res.id : null;
        if (newId){
          // reload and select the saved/created company so Add Item is enabled
          loadCompanies(newId);
        } else {
          loadCompanies();
        }
      })
      .fail(xhr=> alert((xhr.responseJSON && xhr.responseJSON.message) || 'Save failed'));
  });

  // Item events
  $('#ca_btnNewItem').on('click', function(){
    if (!currentCompanyId){
      alert('Please select a competitor first.');
      return;
    }
    $('#ca_itemForm')[0].reset();
    $('#ca_itemId').val('');
    $('#ca_itemCompanyId').val(currentCompanyId);
    const d = $('#ca_defaultDate').val() || new Date().toISOString().slice(0,10);
    $('#ca_itemDate').val(d);
    $('#ca_itemModal').modal('show');
  });

  $('#ca_btnItemFilter').on('click', function(){ loadItems(); });

  // Report events
  $('#ca_btnLoadReport').on('click', loadMonthlyReport);
  $('#ca_btnPrintReport').on('click', printMonthlyReport);

  // Chart events
  $('#ca_btnLoadChart').on('click', loadYearlyChart);

  $tblItems.on('click', '.ca-item-edit', function(){
    const id = $(this).data('id');
    $.get('api/competitor_analysis.php', { action:'list_items', company_id: currentCompanyId }, function(res){
      const rows = res.data||[];
      const row = rows.find(r=> String(r.id)===String(id));
      if (!row) return;
      $('#ca_itemId').val(row.id);
      $('#ca_itemCompanyId').val(row.company_id);
      $('#ca_itemDate').val(row.analysis_date||'');
      $('#ca_itemColor').val(row.color_id||'');
      $('#ca_itemFinish').val(row.finish_id||'');
      $('#ca_itemPrice').val(row.price_per_sqf!=null ? Number(row.price_per_sqf).toFixed(3) : '');
      $('#ca_itemRemarks').val(row.remarks||'');
      $('#ca_itemModal').modal('show');
    });
  });

  $tblItems.on('click', '.ca-item-del', function(){
    if (!confirm('Delete this item?')) return;
    const id = $(this).data('id');
    const fd = new FormData();
    fd.append('csrf', $csrf.val());
    fd.append('action','delete_item');
    fd.append('id', id);
    $.ajax({ url:'api/competitor_analysis.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ loadItems(); })
      .fail(xhr=> alert((xhr.responseJSON && xhr.responseJSON.message) || 'Delete failed'));
  });

  $('#ca_itemForm').on('submit', function(e){
    e.preventDefault();
    const fd = new FormData(this);
    fd.append('action','save_item');
    $.ajax({ url:'api/competitor_analysis.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#ca_itemModal').modal('hide'); loadItems(); })
      .fail(xhr=> alert((xhr.responseJSON && xhr.responseJSON.message) || 'Save failed'));
  });

  // initial
  loadColorFinishOptions(function(){
    loadCompanies();
    setCurrentCompany(null, '');
    const now = new Date();
    $('#ca_chartYear').val(now.getFullYear());
  });
})();
</script>
