<?php
// foods_add.php
session_start();
require_once 'config/db_config.php'; // expects $pdo (PDO)

// ---- Authentication (admins and branch users) ----
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    header("Location: login.php");
    exit();
}

// ---- CSRF Token ----
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---- Helpers ----
function h(string $v): string {
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

// ---- Fetch categories ----
$categories = [];
try {
    $stmt = $pdo->query("SELECT category_id, category_name FROM food_categories ORDER BY category_name");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching categories: " . h($e->getMessage());
}

// ---- Fetch branches for selected category (on form reload after validation failure) ----
$branches = [];
$selected_branches = $_POST['branches'] ?? [];
$category_id = $_POST['category_id'] ?? '';
if ($category_id && is_numeric($category_id)) {
    try {
        $stmt = $pdo->prepare("
            SELECT b.branch_id, b.branch_name 
            FROM branches b
            INNER JOIN branch_categories bc ON b.branch_id = bc.branch_id
            WHERE bc.category_id = :category_id
            ORDER BY b.branch_name
        ");
        $stmt->execute(['category_id' => $category_id]);
        $branches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $errors[] = "Error fetching branches: " . h($e->getMessage());
    }
}

// ---- Form Handling ----
$errors = [];
$food_name = '';
$description = '';
$price = '';
$offer = '';
$is_offer = 0;
$is_available = 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf']) && $_POST['csrf'] === $csrf) {
    $food_name = trim($_POST['food_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $offer = trim($_POST['offer'] ?? '');
    $is_offer = isset($_POST['is_offer']) ? 1 : 0;
    $category_id = $_POST['category_id'] ?? '';
    $is_available = isset($_POST['is_available']) ? 1 : 0;
    $selected_branches = $_POST['branches'] ?? [];

    // Validate inputs
    if (empty($food_name)) {
        $errors[] = "Food name is required.";
    }
    if (empty($category_id) || !is_numeric($category_id)) {
        $errors[] = "Please select a valid category.";
    }
    if (empty($price) || !is_numeric($price) || $price < 0) {
        $errors[] = "Please enter a valid price.";
    }
    if ($is_offer && (empty($offer) || !is_numeric($offer) || $offer < 0 || $offer > 100)) {
        $errors[] = "Offer must be a valid percentage between 0 and 100 when an offer is active.";
    }
    if (!$is_offer && !empty($offer)) {
        $errors[] = "Offer percentage is provided but 'Is Offer' is not checked.";
    }
    if (empty($selected_branches)) {
        $errors[] = "At least one branch must be selected.";
    } else {
        foreach ($selected_branches as $branch_id) {
            if (!is_numeric($branch_id) || $branch_id <= 0) {
                $errors[] = "Invalid branch ID selected.";
                break;
            }
        }
    }

    // Handle image upload
    $image_url = null;
    if (!empty($_FILES['image']['name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $allowed_types = ['image/jpeg', 'image/png'];
        $max_size = 2 * 1024 * 1024; // 2MB
        $file_info = getimagesize($_FILES['image']['tmp_name']);
        if (!$file_info || !in_array($file_info['mime'], $allowed_types)) {
            $errors[] = "Only JPEG or PNG images are allowed.";
        } elseif ($_FILES['image']['size'] > $max_size) {
            $errors[] = "Image size must not exceed 2MB.";
        } else {
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '-' . time() . '.' . $ext;
            $upload_dir = '../Uploads/foods/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $filename)) {
                $image_url = 'Uploads/foods/' . $filename;
            } else {
                $errors[] = "Failed to upload image.";
            }
        }
    } elseif ($_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE) {
        $errors[] = "Image upload error: " . $_FILES['image']['error'];
    }

    // Insert food and branch associations if no errors
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // Insert into foods
            $stmt = $pdo->prepare("
                INSERT INTO foods (category_id, food_name, description, price, offer, is_offer, image_url, is_available, created_at)
                VALUES (:category_id, :food_name, :description, :price, :offer, :is_offer, :image_url, :is_available, NOW())
            ");
            $stmt->execute([
                'category_id' => $category_id,
                'food_name' => $food_name,
                'description' => $description ?: null,
                'price' => $price,
                'offer' => $is_offer ? $offer : null,
                'is_offer' => $is_offer,
                'image_url' => $image_url,
                'is_available' => $is_available
            ]);
            $food_id = $pdo->lastInsertId();

            // Insert into branch_foods
            $status = $is_available ? 'active' : 'inactive';
            $stmt = $pdo->prepare("
                INSERT INTO branch_foods (branch_id, food_id, status)
                VALUES (:branch_id, :food_id, :status)
            ");
            foreach ($selected_branches as $branch_id) {
                $stmt->execute([
                    'branch_id' => $branch_id,
                    'food_id' => $food_id,
                    'status' => $status
                ]);
            }

            $pdo->commit();
            $_SESSION['success'] = "Food '$food_name' created and assigned to selected branches successfully!";
            header("Location: foods_list.php?created=1");
            exit();
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = "Error creating food or assigning branches: " . h($e->getMessage());
        }
    }
}

// JavaScript for dynamic branch loading and Select All
$script = '
<script>
document.addEventListener("DOMContentLoaded", function() {
    const categorySelect = document.getElementById("category_id");
    const branchesContainer = document.getElementById("branchesContainer");
    const selectAllCheckbox = document.getElementById("selectAllBranches");
    const csrfToken = "' . h($csrf) . '";

    function fetchBranches(categoryId) {
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "get_branches_for_category.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.error) {
                        branchesContainer.innerHTML = `<p class="text-danger">Error: ${response.error}</p>`;
                        selectAllCheckbox.disabled = true;
                        return;
                    }
                    let html = "";
                    if (response.length === 0) {
                        html = `<p class="text-danger">No branches available for this category.</p>`;
                        selectAllCheckbox.disabled = true;
                    } else {
                        html = response.map(branch => `
                            <div class="col-md-4">
                                <div class="form-check">
                                    <input class="form-check-input branch-checkbox" type="checkbox" name="branches[]" 
                                           value="${branch.branch_id}" id="branch_${branch.branch_id}"
                                           ${branch.selected ? "checked" : ""}>
                                    <label class="form-check-label" for="branch_${branch.branch_id}">
                                        ${branch.branch_name}
                                    </label>
                                </div>
                            </div>
                        `).join("");
                        selectAllCheckbox.disabled = false;
                    }
                    branchesContainer.innerHTML = html;
                    updateSelectAllState();
                } catch (e) {
                    branchesContainer.innerHTML = `<p class="text-danger">Error loading branches: ${e.message}</p>`;
                    selectAllCheckbox.disabled = true;
                }
            }
        };
        xhr.onerror = function() {
            branchesContainer.innerHTML = `<p class="text-danger">Network error loading branches.</p>`;
            selectAllCheckbox.disabled = true;
        };
        xhr.send(`category_id=${encodeURIComponent(categoryId)}&selected_branches=${encodeURIComponent(JSON.stringify(' . json_encode($selected_branches) . '))}&csrf=${encodeURIComponent(csrfToken)}`);
    }

    function updateSelectAllState() {
        const branchCheckboxes = document.querySelectorAll(".branch-checkbox");
        selectAllCheckbox.checked = branchCheckboxes.length > 0 && Array.from(branchCheckboxes).every(cb => cb.checked);
        selectAllCheckbox.disabled = branchCheckboxes.length === 0;
    }

    // Load branches for initial category (if any)
    if (categorySelect.value) {
        fetchBranches(categorySelect.value);
    }

    // Update branches when category changes
    categorySelect.addEventListener("change", function() {
        branchesContainer.innerHTML = `<p>Loading branches...</p>`;
        selectAllCheckbox.disabled = true;
        fetchBranches(this.value);
    });

    // Handle Select All
    selectAllCheckbox.addEventListener("change", function() {
        document.querySelectorAll(".branch-checkbox").forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // Update Select All state when individual checkboxes change
    branchesContainer.addEventListener("change", function(e) {
        if (e.target.classList.contains("branch-checkbox")) {
            updateSelectAllState();
        }
    });
});
</script>';
?>

<?php include './partials/layouts/layoutTop.php'; ?>

<div class="dashboard-main-body">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
        <h6 class="fw-semibold mb-0">Add Food</h6>
        <ul class="d-flex align-items-center gap-2 flex-wrap">
            <li class="fw-medium">
                <a href="index.php" class="d-flex align-items-center gap-1 hover-text-primary text-truncate">
                    <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon>
                    Dashboard
                </a>
            </li>
            <li>-</li>
            <li class="fw-medium"><a href="foods_list.php" class="hover-text-primary text-truncate">Foods</a></li>
            <li>-</li>
            <li class="fw-medium text-truncate">Add Food</li>
        </ul>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <ul class="mb-0 ps-3">
                <?php foreach ($errors as $error): ?>
                    <li class="text-break"><?= h($error); ?></li>
                <?php endforeach; ?>
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body p-3 p-md-4">
            <h6 class="section-title text-lg mb-3 mb-md-4">Create New Food</h6>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="csrf" value="<?= h($csrf); ?>">
                <div class="row gy-3">
                    <div class="col-12 col-md-6">
                        <label class="form-label fw-medium">Food Name *</label>
                        <input type="text" class="form-control bg-base" name="food_name" value="<?= h($food_name); ?>" required maxlength="255">
                    </div>
                    <div class="col-12 col-md-6">
                        <label class="form-label fw-medium">Category *</label>
                        <select class="form-select bg-base" name="category_id" id="category_id" required>
                            <option value="" disabled <?= empty($category_id) ? 'selected' : ''; ?>>Select Category</option>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?= h($category['category_id']); ?>" <?= $category_id == $category['category_id'] ? 'selected' : ''; ?>>
                                    <span class="text-truncate"><?= h($category['category_name']); ?></span>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Assign to Branches <span class="text-danger">*</span></label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="selectAllBranches">
                            <label class="form-check-label" for="selectAllBranches">Select All Branches</label>
                        </div>
                        <div class="row" id="branchesContainer">
                            <?php if ($branches): ?>
                                <?php foreach ($branches as $branch): ?>
                                    <div class="col-md-4">
                                        <div class="form-check">
                                            <input class="form-check-input branch-checkbox" type="checkbox" name="branches[]" 
                                                   value="<?= (int)$branch['branch_id']; ?>" id="branch_<?= (int)$branch['branch_id']; ?>"
                                                   <?= in_array($branch['branch_id'], $selected_branches) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="branch_<?= (int)$branch['branch_id']; ?>">
                                                <?= h($branch['branch_name']); ?>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php elseif ($category_id): ?>
                                <p class="text-danger">No branches available for this category.</p>
                            <?php else: ?>
                                <p>Please select a category to load available branches.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="col-12 col-md-6">
                        <label class="form-label fw-medium">Price (₹) *</label>
                        <input type="number" step="0.01" min="0" class="form-control bg-base" name="price" value="<?= h($price); ?>" required>
                    </div>
                    <div class="col-12 col-md-6">
                        <label class="form-label fw-medium">Offer (%)</label>
                        <input type="number" step="0.01" min="0" max="100" class="form-control bg-base" name="offer" value="<?= h($offer); ?>" placeholder="e.g., 10.00 for 10% off">
                    </div>
                    <div class="col-12 col-md-6">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" name="is_offer" id="is_offer" <?= $is_offer ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="is_offer">Is Offer Active</label>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Description</label>
                        <textarea class="form-control bg-base" name="description" rows="4" maxlength="1000" placeholder="Enter food description (optional)"><?= h($description); ?></textarea>
                        <small class="form-text text-muted">Max 1000 characters</small>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-medium">Food Image (JPEG/PNG, Max 2MB)</label>
                        <input type="file" class="form-control bg-base" name="image" accept="image/jpeg,image/png">
                        <small class="form-text text-muted">Recommended size: 500x500px</small>
                    </div>
                    <div class="col-12">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_available" id="is_available" <?= $is_available ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="is_available">Is Available</label>
                        </div>
                    </div>
                    <div class="col-12 text-end mt-3">
                        <button type="submit" class="btn btn-primary px-4">Create Food</button>
                        <a href="foods_list.php" class="btn btn-outline-secondary px-4">Cancel</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include './partials/layouts/layoutBottom.php'; ?>