<?php
require_once __DIR__ . '/../includes/auth.php';

$id = (int)($_GET['id'] ?? 0);
$row = ['id'=>0,'project_id'=>0,'category_id'=>0,'subcategory_id'=>0,'name'=>'','description'=>'','remark'=>'','url'=>'','price'=>0];
$images = [];
$titles = [];

if ($id) {
    $row = $conn->query("SELECT * FROM products WHERE id=$id")->fetch_assoc() ?: $row;
    $res = $conn->query("SELECT * FROM product_images WHERE product_id=$id");
    while ($r = $res->fetch_assoc()) $images[] = $r;
    $res = $conn->query("SELECT * FROM product_titles WHERE product_id=$id ORDER BY id");
    while ($r = $res->fetch_assoc()) $titles[] = $r;
}
$pageTitle = $id ? 'Edit Product' : 'Add Product';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $project_id = (int)$_POST['project_id'];
    $category_id = (int)$_POST['category_id'];
    $subcategory_id = (int)$_POST['subcategory_id'];
    $name = trim($_POST['name']);
    $desc = trim($_POST['description']);
    $remark = trim($_POST['remark']);
    $url = trim($_POST['url']);
    $price = (float)$_POST['price'];

    if ($id) {
        $stmt = $conn->prepare("UPDATE products SET project_id=?, category_id=?, subcategory_id=?, name=?, description=?, remark=?, url=?, price=? WHERE id=?");
        $stmt->bind_param('iiissssdi', $project_id, $category_id, $subcategory_id, $name, $desc, $remark, $url, $price, $id);
        $stmt->execute();
        $pid = $id;
    } else {
        $stmt = $conn->prepare("INSERT INTO products (project_id, category_id, subcategory_id, name, description, remark, url, price) VALUES (?,?,?,?,?,?,?,?)");
        $stmt->bind_param('iiissssd', $project_id, $category_id, $subcategory_id, $name, $desc, $remark, $url, $price);
        $stmt->execute();
        $pid = $stmt->insert_id;
    }

    // delete selected images
    if (!empty($_POST['delete_images'])) {
        foreach ($_POST['delete_images'] as $img_id) {
            $img_id = (int)$img_id;
            $r = $conn->query("SELECT image_path FROM product_images WHERE id=$img_id AND product_id=$pid")->fetch_assoc();
            if ($r) { delete_image_file($r['image_path']); $conn->query("DELETE FROM product_images WHERE id=$img_id"); }
        }
    }

    // upload new images
    if (!empty($_FILES['images']['name'][0])) {
        $paths = upload_images($_FILES['images'], 'products');
        foreach ($paths as $p) {
            $stmt = $conn->prepare("INSERT INTO product_images (product_id, image_path) VALUES (?,?)");
            $stmt->bind_param('is', $pid, $p);
            $stmt->execute();
        }
    }

    // titles handling
    if (!empty($_POST['delete_titles'])) {
        foreach ($_POST['delete_titles'] as $tid) {
            $tid = (int)$tid;
            $conn->query("DELETE FROM product_titles WHERE id=$tid AND product_id=$pid");
        }
    }
    if (!empty($_POST['title_id'])) {
        foreach ($_POST['title_id'] as $i => $tid) {
            $tid = (int)$tid;
            $tname = trim($_POST['title_name'][$i] ?? '');
            $tdesc = trim($_POST['title_desc'][$i] ?? '');
            if ($tname === '') continue;
            if ($tid > 0) {
                $stmt = $conn->prepare("UPDATE product_titles SET title_name=?, description=? WHERE id=? AND product_id=?");
                $stmt->bind_param('ssii', $tname, $tdesc, $tid, $pid);
                $stmt->execute();
            } else {
                $stmt = $conn->prepare("INSERT INTO product_titles (product_id, title_name, description) VALUES (?,?,?)");
                $stmt->bind_param('iss', $pid, $tname, $tdesc);
                $stmt->execute();
            }
        }
    }

    flash('success', $id ? 'Product updated' : 'Product added');
    redirect('index.php');
}

$projects = $conn->query("SELECT id, name FROM projects ORDER BY name");
include __DIR__ . '/../includes/header.php';
?>
<h2 class="mb-3"><?= $pageTitle ?></h2>
<div class="card"><div class="card-body">
<form method="post" enctype="multipart/form-data">
  <div class="row g-3">
    <div class="col-md-4">
      <label class="form-label">Project *</label>
      <select name="project_id" id="project_id" class="form-select" required>
        <option value="">-- Select --</option>
        <?php while ($p = $projects->fetch_assoc()): ?>
        <option value="<?= $p['id'] ?>" <?= $row['project_id']==$p['id']?'selected':'' ?>><?= e($p['name']) ?></option>
        <?php endwhile; ?>
      </select>
    </div>
    <div class="col-md-4">
      <label class="form-label">Category *</label>
      <select name="category_id" id="category_id" class="form-select" required data-selected="<?= $row['category_id'] ?>">
        <option value="">-- Select Project First --</option>
      </select>
    </div>
    <div class="col-md-4">
      <label class="form-label">Subcategory *</label>
      <select name="subcategory_id" id="subcategory_id" class="form-select" required data-selected="<?= $row['subcategory_id'] ?>">
        <option value="">-- Select Category First --</option>
      </select>
    </div>
  </div>

  <hr>

  <div class="row g-3">
    <div class="col-md-6"><label class="form-label">Name *</label>
      <input type="text" name="name" class="form-control" value="<?= e($row['name']) ?>" required></div>
    <div class="col-md-3"><label class="form-label">Price</label>
      <input type="number" step="0.01" name="price" class="form-control" value="<?= e($row['price']) ?>"></div>
    <div class="col-md-3"><label class="form-label">URL</label>
      <input type="url" name="url" class="form-control" value="<?= e($row['url']) ?>"></div>
  </div>
  <div class="mb-3 mt-3"><label class="form-label">Description</label>
    <textarea name="description" class="form-control" rows="3"><?= e($row['description']) ?></textarea></div>
  <div class="mb-3"><label class="form-label">Remark</label>
    <textarea name="remark" class="form-control" rows="2"><?= e($row['remark']) ?></textarea></div>

  <?php if ($images): ?>
  <div class="mb-3">
    <label class="form-label">Existing Images</label>
    <div class="d-flex flex-wrap gap-2">
      <?php foreach ($images as $img): ?>
      <div class="text-center">
        <img src="<?= UPLOAD_URL ?>/<?= e($img['image_path']) ?>" class="img-preview"><br>
        <input type="checkbox" name="delete_images[]" value="<?= $img['id'] ?>"> <small class="text-danger">Delete</small>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>
  <div class="mb-3">
    <label class="form-label">Add Images</label>
    <input type="file" name="images[]" class="form-control" multiple accept="image/*">
  </div>

  <hr>
  <h5 class="mb-3">Product Titles <small class="text-muted">(add any number)</small></h5>
  <div id="titles-wrap">
    <?php foreach ($titles as $t): ?>
    <div class="row g-2 mb-2 title-row">
      <input type="hidden" name="title_id[]" value="<?= $t['id'] ?>">
      <div class="col-md-4"><input type="text" name="title_name[]" class="form-control" placeholder="Title name" value="<?= e($t['title_name']) ?>"></div>
      <div class="col-md-7"><textarea name="title_desc[]" class="form-control" rows="1" placeholder="Description"><?= e($t['description']) ?></textarea></div>
      <div class="col-md-1">
        <label class="btn btn-outline-danger btn-sm" title="Mark for delete">
          <input type="checkbox" name="delete_titles[]" value="<?= $t['id'] ?>" hidden onchange="this.parentElement.classList.toggle('active', this.checked); this.closest('.title-row').classList.toggle('opacity-50', this.checked);">
          <i class="bi bi-trash"></i>
        </label>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <button type="button" class="btn btn-outline-primary btn-sm" onclick="addTitle()"><i class="bi bi-plus"></i> Add Title</button>

  <hr>
  <button class="btn btn-primary"><i class="bi bi-save"></i> Save</button>
  <a href="index.php" class="btn btn-secondary">Cancel</a>
</form>
</div></div>

<script>
const BASE = '<?= BASE_URL ?>';

function loadCategories(projectId, selectedId) {
  const sel = document.getElementById('category_id');
  sel.innerHTML = '<option value="">Loading...</option>';
  if (!projectId) { sel.innerHTML = '<option value="">-- Select Project First --</option>'; return; }
  fetch(BASE + '/ajax/get_categories.php?project_id=' + projectId)
    .then(r => r.json()).then(data => {
      sel.innerHTML = '<option value="">-- Select Category --</option>';
      data.forEach(c => {
        const opt = new Option(c.name, c.id);
        if (selectedId && c.id == selectedId) opt.selected = true;
        sel.add(opt);
      });
      sel.dispatchEvent(new Event('change'));
    });
}

function loadSubcategories(categoryId, selectedId) {
  const sel = document.getElementById('subcategory_id');
  sel.innerHTML = '<option value="">Loading...</option>';
  if (!categoryId) { sel.innerHTML = '<option value="">-- Select Category First --</option>'; return; }
  fetch(BASE + '/ajax/get_subcategories.php?category_id=' + categoryId)
    .then(r => r.json()).then(data => {
      sel.innerHTML = '<option value="">-- Select Subcategory --</option>';
      data.forEach(c => {
        const opt = new Option(c.name, c.id);
        if (selectedId && c.id == selectedId) opt.selected = true;
        sel.add(opt);
      });
    });
}

document.getElementById('project_id').addEventListener('change', function() {
  loadCategories(this.value, document.getElementById('category_id').dataset.selected);
});
document.getElementById('category_id').addEventListener('change', function() {
  loadSubcategories(this.value, document.getElementById('subcategory_id').dataset.selected);
});

// Initial load on edit
window.addEventListener('DOMContentLoaded', () => {
  const pid = document.getElementById('project_id').value;
  if (pid) loadCategories(pid, document.getElementById('category_id').dataset.selected);
});

function addTitle() {
  const wrap = document.getElementById('titles-wrap');
  const div = document.createElement('div');
  div.className = 'row g-2 mb-2 title-row';
  div.innerHTML = `
    <input type="hidden" name="title_id[]" value="0">
    <div class="col-md-4"><input type="text" name="title_name[]" class="form-control" placeholder="Title name"></div>
    <div class="col-md-7"><textarea name="title_desc[]" class="form-control" rows="1" placeholder="Description"></textarea></div>
    <div class="col-md-1"><button type="button" class="btn btn-outline-danger btn-sm" onclick="this.closest('.title-row').remove()"><i class="bi bi-trash"></i></button></div>
  `;
  wrap.appendChild(div);
}
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
