<?php
$pdo = require __DIR__ . '/../config/db.php';
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
$suppliers = $pdo->query('SELECT name FROM suppliers ORDER BY name')->fetchAll(PDO::FETCH_COLUMN);
$formats = $pdo->query('SELECT name FROM formats ORDER BY name')->fetchAll(PDO::FETCH_COLUMN);
$market = $pdo->query('SELECT name FROM market ORDER BY name')->fetchAll(PDO::FETCH_COLUMN);
$competitors = $pdo->query('SELECT name FROM competitors ORDER BY name')->fetchAll(PDO::FETCH_COLUMN);
$role = $_SESSION['role'] ?? null;
?>
<div id="formMessage" class="alert d-none" role="alert"></div>
<form id="addSiteForm" method="post" enctype="multipart/form-data" style="font-size:0.92em;">
  <input type="hidden" name="action" value="add">
  <div class="row">
    <!-- Left Column -->
    <div class="col-12 col-md-6">
      <h4 class="mt-4 mb-1 text-primary" style="font-size:1.2em;text-align:right;">Site Information</h4>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Supplier</div>
        <div class="col-7">
          <select name="supplier" class="form-control form-control-sm" required>
            <option value="">Supplier Name</option>
            <?php foreach ($suppliers as $s): ?>
              <option value="<?= htmlspecialchars($s) ?>"><?= htmlspecialchars($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Type</div>
        <div class="col-7"><select name="type" class="form-control form-control-sm" required>
            <option value="">Type of Format</option>
            <option value="Indoor">Indoor</option>
            <option value="Outdoor">Outdoor</option>
          </select></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Format</div>
        <div class="col-7">
          <select name="format" id="format-select" class="form-control form-control-sm" required>
            <option value="">Format of Site</option>
            <?php foreach ($formats as $f): ?>
              <option value="<?= htmlspecialchars($f) ?>"><?= htmlspecialchars($f) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Size WxH (meter)</div>
        <div class="col-3"><input type="number" step="0.01" name="size_x_m" class="form-control form-control-sm" placeholder="Width"></div>
        <div class="col-1 text-center">x</div>
        <div class="col-3"><input type="number" step="0.01" name="size_y_m" class="form-control form-control-sm" placeholder="Height"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Size WxH (pixel)</div>
        <div class="col-3"><input type="number" name="size_x_p" class="form-control form-control-sm" placeholder="Width"></div>
        <div class="col-1 text-center">x</div>
        <div class="col-3"><input type="number" name="size_y_p" class="form-control form-control-sm" placeholder="Height"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Image</div>
        <div class="col-7"><input type="file" name="image_base_upload" class="form-control form-control-sm" accept="image/*"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Programmatic Enable</div>
        <div class="col-7">
          <select name="pdooh" class="form-control form-control-sm"
            <?php if (!empty($addMode)) echo 'disabled'; ?>>
            <option value="">Programmatic Adaptation</option>
            <option value="Yes" <?php if (empty($addMode) && isset($current['pdooh']) && $current['pdooh'] === 'Yes') echo 'selected'; ?>>Yes</option>
            <option value="No" <?php if (!empty($addMode) || (isset($current['pdooh']) && $current['pdooh'] === 'No')) echo 'selected'; ?>>No</option>
          </select>
          <?php if (!empty($addMode)): ?>
            <input type="hidden" name="pdooh" value="No">
          <?php endif; ?>
        </div>
      </div>
    </div>
    <!-- Right Column -->
    <div class="col-12 col-md-6">
      <h4 class="mt-4 mb-1 text-primary" style="font-size:1.2em;text-align:right;">Site Location</h4>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Market</div>
        <div class="col-7">
          <select name="market" class="form-control form-control-sm" required>
            <option value="">Select Market</option>
            <?php foreach ($market as $m): ?>
              <option value="<?= htmlspecialchars($m) ?>"><?= htmlspecialchars($m) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">District</div>
        <div class="col-7"><input type="text" name="district" class="form-control form-control-sm" placeholder="eg. Tan Binh, 3, 1"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Ward</div>
        <div class="col-7"><input type="text" name="ward" class="form-control form-control-sm" placeholder="eg. Ben Nghe"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Street Name</div>
        <div class="col-7"><input type="text" name="street" class="form-control form-control-sm" placeholder="eg. Vo Thi Sau"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Street Number</div>
        <div class="col-7"><input type="text" name="street_no" class="form-control form-control-sm" placeholder="eg. 156"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Format Coordination</div>
        <div class="col-7"><input type="text" name="format_coordination" class="form-control form-control-sm" placeholder="Input Google Map Location link"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Availability</div>
        <div class="col-7"><input type="date" placeholder="Available Date" name="availability" class="form-control form-control-sm"></div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Brand Owning</div>
        <div class="col-7"><input type="text" placeholder="On-Site Brand Name" name="current_own" class="form-control form-control-sm"></div>
      </div>
    </div>
    <div class="col-12 d-flex justify-content-center mt-3 mb-2">
      <button type="submit" class="btn btn-success px-4">Add Site</button>
    </div>
  </div>
</form>

<!-- Active Message Modal -->
<?php include __DIR__ . '/common.php'; ?>
<script src="/ooh_project/modules/common.js"></script>
<script>
  // POST ADD FORMAT
  function addSite(form) {
    var data = new FormData(form);
    ['image_base', 'availability', 'current_own', 'image_comp', 'plan_cost', 'buy_type', 'evaluate_score', 'buy_cost', 'profit_lost'].forEach(function(f) {
      if (!form[f] || form[f].value === '') data.set(f, '');
    });
    fetch('/ooh_project/handler/site_crud.php', {
        method: 'POST',
        body: data
      })
      .then(res => res.json())
      .then(resp => {
        if (resp.success) {
          showMessageModal('Site added successfully!', 'success');
          form.reset();
          setTimeout(function() {
            location.reload();
          }, 1200);
        } else {
          showMessageModal(resp.error || 'Failed to add site. Please check your input.', 'danger');
        }
      })
      .catch(() => showMessageModal('Server error. Please try again.', 'danger'));
  }

  // Attach listeners
  // Only Add Site logic here
  if (document.getElementById('addSiteForm')) {
    document.getElementById('addSiteForm').addEventListener('submit', function(e) {
      e.preventDefault();
      addSite(e.target);
    });
  }

  // Format VND fields with thousand separator
  function formatVND(input) {
    var value = input.value.replace(/\D/g, '');
    input.value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  }
  document.getElementById('supplier_cost').addEventListener('input', function() {
    formatVND(this);
  });
  document.getElementById('plan_cost').addEventListener('input', function() {
    formatVND(this);
  });
  document.getElementById('buy_cost').addEventListener('input', function() {
    formatVND(this);
  });
  // Enable Duration Buying only for certain formats
  var formatSelect = document.getElementById('format-select');
  if (formatSelect) {
    formatSelect.addEventListener('change', function() {
      var enabledFormats = ['Big LED', 'LCD', 'Digital Poster', 'Standee Screen', 'Sky LED'];
      var durationBuy = document.getElementById('duration_buy');
      if (enabledFormats.indexOf(this.value) !== -1) {
        durationBuy.disabled = false;
      } else {
        durationBuy.disabled = true;
        durationBuy.value = '';
      }
    });
  }
  // Auto-calculate P&L
  function calcPL() {
    var plan = document.getElementById('plan_cost').value.replace(/,/g, '');
    var buy = document.getElementById('buy_cost').value.replace(/,/g, '');
    plan = parseInt(plan) || 0;
    buy = parseInt(buy) || 0;
    var pl = buy > 0 ? ((plan - buy) / buy) * 100 : 0;
    document.getElementById('profit_lost').value = pl.toFixed(2) + '%';
  }
  document.getElementById('plan_cost').addEventListener('input', calcPL);
  document.getElementById('buy_cost').addEventListener('input', calcPL);



  // Image upload for Site Image
  // Robust image upload event for Add Modal using event delegation
  document.addEventListener('change', function(e) {
    var input = e.target;
    // For Add Modal: Site Image
    if (input && input.name === 'image_base_upload' && input.closest('#addSiteModal')) {
      var file = input.files[0];
      if (!file) return;
      var formData = new FormData();
      formData.append('image', file);
      formData.append('image_type', 'image_base');
      fetch('/ooh_project/handler/upload_image.php', {
          method: 'POST',
          body: formData
        })
        .then(response => response.text())
        .then(result => {
          if (result.startsWith('success:')) {
            var hidden = document.getElementById('image_base_hidden');
            if (hidden) hidden.value = file.name;
            var msgEl = document.getElementById('formMessage');
            if (msgEl) {
              msgEl.className = 'alert alert-success';
              msgEl.textContent = 'Image uploaded successfully!';
              msgEl.classList.remove('d-none');
            }
          } else {
            alert(result);
          }
        });
    }
  });
</script>