<?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);
$role = $_SESSION['role'] ?? null;
?>
<div id="formMessage" class="alert d-none" role="alert"></div>
<form id="addFormatForm" method="post" enctype="multipart/form-data" style="font-size:0.92em;">
  <input type="hidden" name="action" value="add">
  <div class="row">
    <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_y" 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"><option value="">Programmatic Adaptation</option><option value="Yes">Yes</option><option value="No">No</option></select></div></div>
      <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"><input type="text" name="market" class="form-control form-control-sm" placeholder="eg. Ho Chi Minh/ Ha Noi"></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>
    <div class="col-12 col-md-6">
      <h4 class="mt-4 mb-1 text-primary" style="font-size:1.2em;text-align:right;">Selling Information</h4>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">Supplier Cost (VND)</div><div class="col-7"><input type="text" placeholder="Ratecard Cost" name="supplier_cost" id="supplier_cost" class="form-control form-control-sm" pattern="[0-9,]+"></div></div>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">Duration by Cost</div><div class="col-7"><input type="text" placeholder="eg. 6 months" name="duration" class="form-control form-control-sm"></div></div>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">Duration Buying</div><div class="col-7"><select name="duration_buy" id="duration_buy" class="form-control form-control-sm" disabled><option value="">Duration Buying</option><option value="1 hour/day">1 hour/day</option><option value="2 hours/day">2 hours/day</option><option value="3 hours/day">3 hours/day</option></select></div></div>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">Discount (%)</div><div class="col-7"><input type="number" placeholder="Discount by Duration" step="0.01" name="discount" id="discount" class="form-control form-control-sm"></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 Competitor's Name" name="current_own" class="form-control form-control-sm"></div></div>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">Competitor Image</div><div class="col-7"><input type="file" name="image_comp_upload" class="form-control form-control-sm" accept="image/*"<?php if (isset($addMode) && $addMode) echo ' disabled'; ?>><input type="hidden" name="image_comp" id="image_comp_hidden"></div></div>
      <h4 class="mt-4 mb-1 text-primary" style="font-size:1.2em;text-align:right;">Planning Information</h4>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Plan Cost (VND)</div>
        <div class="col-7">
          <input type="text" name="plan_cost" id="plan_cost" class="form-control form-control-sm" pattern="[0-9,]+"
          <?php if ($role !== 'admin') echo 'readonly tabindex="-1" style="pointer-events:none;background:#eee;"'; ?>>
        </div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Buying Type</div>
        <div class="col-7">
          <select name="buy_type" class="form-control form-control-sm"
          <?php if ($role !== 'admin') echo 'disabled tabindex="-1" style="pointer-events:none;background:#eee;"'; ?>>
            <option value="">Buying Type</option>
            <option value="Direct Buy">Direct Buy</option>
            <option value="Added Value">Added Value</option>
          </select>
        </div>
      </div>
      <div class="row mb-2 align-items-center">
        <div class="col-5 text-end pe-1">Site Score</div>
        <div class="col-7">
          <input type="number" step="0.1" name="evaluate_score" class="form-control form-control-sm"
          <?php if ($role !== 'admin') echo 'readonly tabindex="-1" style="pointer-events:none;background:#eee;"'; ?>>
        </div>
      </div>
      <?php if ($role === 'admin'): ?>
      <h4 class="mt-4 mb-1 text-primary" style="font-size:1.2em;text-align:right;">Performance</h4>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">Buy Cost (VND)</div><div class="col-7"><input type="text" name="buy_cost" id="buy_cost" class="form-control form-control-sm" pattern="[0-9,]+"></div></div>
      <div class="row mb-2 align-items-center"><div class="col-5 text-end pe-1">P&L (%)</div><div class="col-7"><input type="text" name="profit_lost" id="profit_lost" class="form-control form-control-sm" readonly disabled></div></div>
      <?php endif; ?>
    </div>
    <div class="col-12 d-flex justify-content-center mt-3 mb-2">
      <button type="submit" class="btn btn-success px-4">Add Format</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 addFormat(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/format_crud.php', {
        method: 'POST',
        body: data
    })
    .then(res => res.json())
    .then(resp => {
        if (resp.success) {
            showMessageModal('Format added successfully!', 'success');
            form.reset();
            setTimeout(function() { location.reload(); }, 1200);
        } else {
            showMessageModal(resp.error || 'Failed to add format. Please check your input.', 'danger');
        }
    })
    .catch(() => showMessageModal('Server error. Please try again.', 'danger'));
}

// Attach listeners
// Only Add Format logic here
if (document.getElementById('addFormatForm')) {
    document.getElementById('addFormatForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addFormat(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 Format Image
// Robust image upload event for Add Modal using event delegation
document.addEventListener('change', function(e) {
    var input = e.target;
    // For Add Modal: Format Image
    if (input && input.name === 'image_base_upload' && input.closest('#addFormatModal')) {
        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>
