<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';
require_once __DIR__ . '/../config/database.php';

if (empty($_GET['product_id'])) {
    die('Invalid product');
}
$productId = (int)$_GET['product_id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Manage Images']); ?>
<?php include '../partials/head-css.php'; ?>
</head>

<body>
<div id="layout-wrapper">
<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables('../partials/page-title.php', [
    'title_sub' => 'Catalog',
    'title'     => 'Manage Images'
]); ?>

<div class="mb-3">
    <a href="<?= ADMIN_BASE_URL ?>retail-products/view.php?id=<?= $productId ?>" class="btn btn-light">
        <i class="bi bi-arrow-left me-1"></i> Back to Product
    </a>
</div>

<!-- ================= ADD IMAGE ================= -->
<div class="card mb-4">
<div class="card-header fw-semibold">Add Image</div>
<div class="card-body">
<form id="uploadForm" enctype="multipart/form-data">
<input type="hidden" name="product_id" value="<?= $productId ?>">

<div class="row g-3 align-items-end">
    <div class="col-md-3">
        <label class="form-label">Image *</label>
        <input type="file" name="image" class="form-control" required>
    </div>
    <div class="col-md-2">
        <label class="form-label">Alt</label>
        <input type="text" name="alt_text" class="form-control">
    </div>
    <div class="col-md-2">
        <label class="form-label">Caption</label>
        <input type="text" name="caption" class="form-control">
    </div>
    <div class="col-md-2">
        <label class="form-label">Order</label>
        <input type="number" name="sort_order" class="form-control" value="1" min="1" required>
    </div>
    <div class="col-md-2">
        <div class="form-check mt-4">
            <input class="form-check-input" type="checkbox" name="is_featured" value="1">
            <label class="form-check-label">Featured</label>
        </div>
    </div>
    <div class="col-md-1">
        <button class="btn btn-success w-100 mt-4"><i class="bi bi-upload"></i></button>
    </div>
</div>
</form>
</div>
</div>

<!-- ================= LIST ================= -->
<div class="card">
<div class="card-body table-responsive">
<table class="table align-middle">
<thead>
<tr>
    <th>#</th>
    <th>Image</th>
    <th>Alt</th>
    <th>Caption</th>
    <th>Featured</th>
    <th>Order</th>
    <th>Status</th>
    <th>Actions</th>
</tr>
</thead>
<tbody id="imageRows">
<tr><td colspan="8" class="text-center text-muted">Loading…</td></tr>
</tbody>
</table>
</div>
</div>

</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>

<!-- ================= STATUS MODAL ================= -->
<div class="modal fade" id="statusModal" tabindex="-1">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header"><h6 class="modal-title">Update Status</h6></div>
<div class="modal-body">
<input type="hidden" id="status_image_id">
<select id="new_status" class="form-select">
    <option value="Active">Active</option>
    <option value="InActive">InActive</option>
</select>
<button class="btn btn-primary w-100 mt-3" onclick="updateStatus()">Update</button>
</div>
</div>
</div>
</div>

<!-- ================= EDIT MODAL ================= -->
<div class="modal fade" id="editModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header"><h6 class="modal-title">Edit Image</h6></div>
<div class="modal-body">
<input type="hidden" id="edit_image_id">

<label class="form-label">Alt</label>
<input type="text" id="edit_alt" class="form-control">

<label class="form-label mt-2">Caption</label>
<input type="text" id="edit_caption" class="form-control">

<label class="form-label mt-2">Order</label>
<input type="number" id="edit_order" class="form-control" min="1">

<div class="form-check mt-2">
    <input type="checkbox" id="edit_featured" class="form-check-input">
    <label class="form-check-label">Featured</label>
</div>

<button class="btn btn-success w-100 mt-3" onclick="saveEdit()">Save</button>
</div>
</div>
</div>
</div>

<!-- ================= DELETE MODAL ================= -->
<div class="modal fade" id="deleteModal" tabindex="-1">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-danger text-white"><h6 class="modal-title">Delete Image</h6></div>
<div class="modal-body text-center">
<input type="hidden" id="delete_image_id">
<p>This action is irreversible.</p>
<button class="btn btn-danger w-100" onclick="confirmDelete()">Delete</button>
</div>
</div>
</div>
</div>

<script>
const PRODUCT_ID = <?= $productId ?>;
const API_LIST   = "<?= ADMIN_BASE_URL ?>api/retail-products/images/list.php";
const API_UPLOAD = "<?= ADMIN_BASE_URL ?>api/retail-products/upload-image.php";
const API_EDIT   = "<?= ADMIN_BASE_URL ?>api/retail-products/images/edit.php";
const API_STATUS = "<?= ADMIN_BASE_URL ?>api/retail-products/images/update-status.php";
const API_DELETE = "<?= ADMIN_BASE_URL ?>api/retail-products/images/delete.php";

let statusModal, editModal, deleteModal;

document.addEventListener('DOMContentLoaded', () => {
    statusModal = new bootstrap.Modal('#statusModal');
    editModal   = new bootstrap.Modal('#editModal');
    deleteModal = new bootstrap.Modal('#deleteModal');
    loadImages();
});

/* ================= LOAD ================= */
function loadImages() {
    fetch(API_LIST + '?product_id=' + PRODUCT_ID)
    .then(r => r.json())
    .then(res => {
        const tbody = document.getElementById('imageRows');
        tbody.innerHTML = '';
        if (!res.data.images.length) {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center">No images</td></tr>';
            return;
        }
        res.data.images.forEach((img, i) => {
            tbody.innerHTML += `
<tr>
<td>${i+1}</td>
<td><img src="<?= APP_ROOT ?>${img.image_path}" width="60"></td>
<td>${img.alt_text ?? '-'}</td>
<td>${img.caption ?? '-'}</td>
<td>${img.is_featured ? 'Yes' : 'No'}</td>
<td>${img.sort_order}</td>
<td>
<span class="badge bg-secondary cursor-pointer"
onclick="openStatus(${img.id}, '${img.status}')">${img.status}</span>
</td>
<td class="d-flex gap-1">
<button class="btn btn-sm btn-light-warning"
onclick='openEdit(${JSON.stringify(img)})'>
<i class="bi bi-pencil"></i></button>
<button class="btn btn-sm btn-light-danger"
onclick="openDelete(${img.id})"><i class="bi bi-trash"></i></button>
</td>
</tr>`;
        });
    });
}

/* ================= STATUS ================= */
function openStatus(id, status) {
    document.getElementById('status_image_id').value = id;
    document.getElementById('new_status').value = status;
    statusModal.show();
}
function updateStatus() {
    fetch(API_STATUS, {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({
            image_id: document.getElementById('status_image_id').value,
            status: document.getElementById('new_status').value
        })
    }).then(()=>{ statusModal.hide(); loadImages(); });
}

/* ================= EDIT ================= */
function openEdit(img) {
    document.getElementById('edit_image_id').value = img.id;
    document.getElementById('edit_alt').value = img.alt_text ?? '';
    document.getElementById('edit_caption').value = img.caption ?? '';
    document.getElementById('edit_order').value = img.sort_order;
    document.getElementById('edit_featured').checked = img.is_featured == 1;
    editModal.show();
}
function saveEdit() {
    fetch(API_EDIT, {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({
            image_id: document.getElementById('edit_image_id').value,
            alt_text: document.getElementById('edit_alt').value,
            caption: document.getElementById('edit_caption').value,
            sort_order: document.getElementById('edit_order').value,
            is_featured: document.getElementById('edit_featured').checked ? 1 : 0,
            product_id: PRODUCT_ID
        })
    }).then(r=>r.json()).then(res=>{
        if(res.confirm){
            if(confirm(res.message)){
                saveEditForce();
            }
            return;
        }
        editModal.hide();
        loadImages();
    });
}
function saveEditForce(){
    fetch(API_EDIT+'?force=1',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({
            image_id: document.getElementById('edit_image_id').value,
            alt_text: document.getElementById('edit_alt').value,
            caption: document.getElementById('edit_caption').value,
            sort_order: document.getElementById('edit_order').value,
            is_featured: 1,
            product_id: PRODUCT_ID
        })
    }).then(()=>{ editModal.hide(); loadImages(); });
}

/* ================= DELETE ================= */
function openDelete(id){ document.getElementById('delete_image_id').value=id; deleteModal.show(); }
function confirmDelete(){
    fetch(API_DELETE,{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({image_id:document.getElementById('delete_image_id').value})
    }).then(()=>{ deleteModal.hide(); loadImages(); });
}
</script>

</body>
</html>
