<?php
session_start();
require_once 'config/db_config.php';

// ---- Security -------------------------------------------------
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---- Init ----------------------------------------------------
$errors = $success = '';
$branch_name = $address = $city = $state = $country = '';
$import_all = $third_party = 0;

// ---- POST ----------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $csrf) {
        $errors[] = "Invalid CSRF token.";
    } else {
        // ----- Basic fields -----
        $branch_name = trim($_POST['branch_name'] ?? '');
        $address     = trim($_POST['address'] ?? '');
        $city        = trim($_POST['city'] ?? '');
        $state       = trim($_POST['state'] ?? '');
        $country     = trim($_POST['country'] ?? '');
        $import_all  = isset($_POST['import_all']) ? 1 : 0;
        $third_party = isset($_POST['third_party']) ? 1 : 0;

        // ----- Validation -----
        if (empty($branch_name)) $errors[] = "Branch name is required.";
        if (empty($address))     $errors[] = "Address is required.";
        if (empty($city))        $errors[] = "City is required.";
        if (empty($state))       $errors[] = "State is required.";
        if (empty($country))     $errors[] = "Country is required.";

        // ----- Branch image (optional) -----
        $image_url = null;
        if (isset($_FILES['branch_image']) && $_FILES['branch_image']['error'] !== UPLOAD_ERR_NO_FILE) {
            $file = $_FILES['branch_image'];
            $allowed = ['image/jpeg','image/jpg','image/png','image/gif'];
            $max = 2*1024*1024; // 2 MB
            if (!in_array($file['type'],$allowed)) {
                $errors[] = "Branch image: only JPEG/PNG/GIF allowed.";
            } elseif ($file['size'] > $max) {
                $errors[] = "Branch image must be ≤ 2 MB.";
            } else {
                $dir = 'uploads/branches/';
                if (!is_dir($dir)) mkdir($dir,0755,true);
                $ext = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
                $name = uniqid().'.'.$ext;
                $path = $dir.$name;
                if (move_uploaded_file($file['tmp_name'],$path)) {
                    $image_url = $path;
                } else {
                    $errors[] = "Failed to upload branch image.";
                }
            }
        }

        // ----- LOGO – ONLY FOR THIRD-PARTY -----
        $logo_url = null;
        if ($third_party) {
            // REQUIRED
            if (!isset($_FILES['branch_logo']) || $_FILES['branch_logo']['error'] === UPLOAD_ERR_NO_FILE) {
                $errors[] = "Logo is required for third-party branches.";
            } else {
                $f = $_FILES['branch_logo'];
                $allowedLogo = ['image/jpeg','image/jpg','image/png'];
                $maxLogo = 500*1024; // 500 KB
                if (!in_array($f['type'],$allowedLogo)) {
                    $errors[] = "Logo: only JPEG/PNG allowed.";
                } elseif ($f['size'] > $maxLogo) {
                    $errors[] = "Logo must be ≤ 500 KB.";
                } else {
                    $dir = 'uploads/logos/';
                    if (!is_dir($dir)) mkdir($dir,0755,true);
                    $ext = strtolower(pathinfo($f['name'],PATHINFO_EXTENSION));
                    $name = uniqid().'.'.$ext;
                    $path = $dir.$name;
                    if (move_uploaded_file($f['tmp_name'],$path)) {
                        $logo_url = $path;
                    } else {
                        $errors[] = "Failed to upload logo.";
                    }
                }
            }
        }

        // ----- INSERT -------------------------------------------------
        if (empty($errors)) {
            try {
                $pdo->beginTransaction();

                $sql = "INSERT INTO branches
                        (branch_name, address, city, state, country, image_url, logo, third_party)
                        VALUES
                        (:branch_name, :address, :city, :state, :country, :image_url, :logo, :third_party)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    'branch_name' => $branch_name,
                    'address'     => $address,
                    'city'        => $city,
                    'state'       => $state,
                    'country'     => $country,
                    'image_url'   => $image_url,
                    'logo'        => $logo_url,
                    'third_party' => $third_party
                ]);
                $branch_id = $pdo->lastInsertId();

                // ----- Import all categories/foods (optional) -----
                if ($import_all) {
                    // categories
                    $cats = $pdo->query("SELECT category_id FROM food_categories")->fetchAll(PDO::FETCH_COLUMN);
                    if ($cats) {
                        $ins = $pdo->prepare("INSERT INTO branch_categories (branch_id, category_id) VALUES (:b,:c)");
                        foreach ($cats as $c) $ins->execute(['b'=>$branch_id,'c'=>$c]);
                    }
                    // foods
                    $foods = $pdo->query("SELECT food_id FROM foods")->fetchAll(PDO::FETCH_COLUMN);
                    if ($foods) {
                        $ins = $pdo->prepare("INSERT INTO branch_foods (branch_id, food_id) VALUES (:b,:f)");
                        foreach ($foods as $f) $ins->execute(['b'=>$branch_id,'f'=>$f]);
                    }
                }

                $pdo->commit();
                $success = "Branch created successfully!"
                         . ($import_all ? " All items imported." : "")
                         . ($third_party ? " (Third-Party with logo)." : "");
                // reset form
                $branch_name = $address = $city = $state = $country = '';
                $import_all = $third_party = 0;
            } catch (PDOException $e) {
                $pdo->rollBack();
                $errors[] = "DB error: ".$e->getMessage();
            }
        }
    }
}
?>
<?php include './partials/layouts/layoutTop.php' ?>

<style>
/* hide logo section for own branches */
#logoSection { display:none; }
#logoSection.show { display:block; }
.logo-preview {
    max-width:120px; max-height:60px;
    object-fit:contain; border:2px dashed #dee2e6;
    border-radius:8px; background:#f8f9fa; padding:8px;
}
</style>

<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">Create New Branch</h6>
        <ul class="d-flex align-items-center gap-2">
            <li class="fw-medium"><a href="index.php" class="d-flex align-items-center gap-1 hover-text-primary"><iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon>Dashboard</a></li>
            <li>-</li>
            <li class="fw-medium">Create Branch</li>
        </ul>
    </div>

    <div class="card border">
        <div class="card-body p-24">
            <h6 class="section-title text-lg mb-16">Add Branch Details</h6>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?=htmlspecialchars($success)?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($errors): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <ul class="mb-0">
                        <?php foreach($errors as $e): ?><li><?=htmlspecialchars($e)?></li><?php endforeach; ?>
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <form action="create_branch.php" method="POST" enctype="multipart/form-data" id="branchForm">
                <input type="hidden" name="csrf" value="<?=htmlspecialchars($csrf)?>">

                <div class="row gy-4">

                    <!-- Basic fields -->
                    <div class="col-md-6"><label class="form-label fw-medium">Branch Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control bg-base" name="branch_name" value="<?=htmlspecialchars($branch_name)?>" required></div>
                    <div class="col-md-6"><label class="form-label fw-medium">Address <span class="text-danger">*</span></label>
                        <input type="text" class="form-control bg-base" name="address" value="<?=htmlspecialchars($address)?>" required></div>

                    <div class="col-md-4"><label class="form-label fw-medium">City <span class="text-danger">*</span></label>
                        <input type="text" class="form-control bg-base" name="city" value="<?=htmlspecialchars($city)?>" required></div>
                    <div class="col-md-4"><label class="form-label fw-medium">State <span class="text-danger">*</span></label>
                        <input type="text" class="form-control bg-base" name="state" value="<?=htmlspecialchars($state)?>" required></div>
                    <div class="col-md-4"><label class="form-label fw-medium">Country <span class="text-danger">*</span></label>
                        <input type="text" class="form-control bg-base" name="country" value="<?=htmlspecialchars($country)?>" required></div>

                    <!-- Branch image (optional) -->
                    <div class="col-12"><label class="form-label fw-medium">Branch Image (Optional)</label>
                        <input type="file" class="form-control bg-base" name="branch_image" accept="image/jpeg,image/png,image/gif">
                        <small class="text-secondary-light">JPEG/PNG/GIF ≤ 2 MB</small></div>

                    <!-- Third-Party checkbox -->
                    <div class="col-12">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="third_party" name="third_party" value="1" <?= $third_party ? 'checked' : '' ?>>
                            <label class="form-check-label" for="third_party">Third-Party Branch</label>
                        </div>
                        <small class="text-secondary-light">Check if operated by a franchise/partner. <strong>Logo required.</strong></small>
                    </div>

                    <!-- LOGO – shown only for third-party -->
                    <div class="col-12" id="logoSection">
                        <label class="form-label fw-medium">Branch Logo <span class="text-danger">*</span></label>
                        <div class="d-flex gap-3 align-items-center">
                            <input type="file" class="form-control bg-base" id="branch_logo" name="branch_logo" accept="image/jpeg,image/png" required>
                            <div id="logoPreview" class="logo-preview d-none">
                                <img src="" alt="preview" class="img-fluid">
                            </div>
                        </div>
                        <small class="text-secondary-light">JPEG/PNG ≤ 500 KB. <strong>Recommended 300 × 150 px (16:9)</strong></small>
                    </div>

                    <!-- Import all -->
                    <div class="col-12">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="import_all" name="import_all" value="1" <?= $import_all ? 'checked' : '' ?>>
                            <label class="form-check-label" for="import_all">Import All Categories & Foods</label>
                        </div>
                    </div>

                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-primary bg-primary-600 hover-bg-primary-700 text-white">Create Branch</button>
                        <a href="index.php" class="btn btn-outline-secondary">Cancel</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include './partials/layouts/layoutBottom.php' ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const thirdPartyChk = document.getElementById('third_party');
    const logoSection   = document.getElementById('logoSection');
    const logoInput     = document.getElementById('branch_logo');
    const logoPreview   = document.getElementById('logoPreview');

    // Toggle visibility & required flag
    function toggleLogo() {
        const show = thirdPartyChk.checked;
        logoSection.classList.toggle('show', show);
        logoInput.required = show;
        if (!show) {
            logoInput.value = '';
            logoPreview.classList.add('d-none');
        }
    }
    toggleLogo();
    thirdPartyChk.addEventListener('change', toggleLogo);

    // Live preview
    logoInput.addEventListener('change', e => {
        const file = e.target.files[0];
        if (!file) return;
        if (file.size > 512000) { alert('Logo ≤ 500 KB'); e.target.value=''; return; }
        const reader = new FileReader();
        reader.onload = ev => {
            logoPreview.querySelector('img').src = ev.target.result;
            logoPreview.classList.remove('d-none');
        };
        reader.readAsDataURL(file);
    });
});
</script>