<?php
session_start();
include 'php/db_connection.php';

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));
}

$errors   = [];
$editData = null;

// ===================== DELETE =====================
if (isset($_GET['delete']) && ctype_digit($_GET['delete'])) {
    $del_id = intval($_GET['delete']);
    $stmt = $con->prepare("DELETE FROM shop_reg WHERE id = ?");
    $stmt->bind_param("i", $del_id);
    $stmt->execute();
    header("Location: shop_reg.php?msg=deleted");
    exit();
}

// ===================== EDIT লোড =====================
if (isset($_GET['edit']) && ctype_digit($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $con->prepare("SELECT * FROM shop_reg WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $editData = $stmt->get_result()->fetch_assoc();
    if (!$editData) die("ডাটা পাওয়া যায়নি! <a href='shop_reg.php'>ফিরে যান</a>");
}

// ===================== INSERT =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'insert') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die("CSRF যাচাই ব্যর্থ!");
    }
    $shop_name    = trim(htmlspecialchars($_POST['shop_name']    ?? '', ENT_QUOTES, 'UTF-8'));
    $shop_address = trim(htmlspecialchars($_POST['shop_address'] ?? '', ENT_QUOTES, 'UTF-8'));
    $shop_mobile  = trim($_POST['shop_mobile'] ?? '');

    if (empty($shop_name))    $errors[] = "শপের নাম দিন।";
    if (empty($shop_address)) $errors[] = "শপের ঠিকানা দিন।";
    if (!preg_match('/^[0-9+\-\s]{7,20}$/', $shop_mobile)) $errors[] = "সঠিক মোবাইল নম্বর দিন।";

    if (empty($errors)) {
        $stmt = $con->prepare("INSERT INTO shop_reg (shop_name, shop_address, shop_mobile) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $shop_name, $shop_address, $shop_mobile);
        if ($stmt->execute()) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            header("Location: shop_reg.php?msg=added");
            exit();
        } else {
            $errors[] = "ডাটা সেভ ব্যর্থ হয়েছে।";
        }
    }
}

// ===================== UPDATE =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die("CSRF যাচাই ব্যর্থ!");
    }
    $up_id        = intval($_POST['edit_id']);
    $shop_name    = trim(htmlspecialchars($_POST['shop_name']    ?? '', ENT_QUOTES, 'UTF-8'));
    $shop_address = trim(htmlspecialchars($_POST['shop_address'] ?? '', ENT_QUOTES, 'UTF-8'));
    $shop_mobile  = trim($_POST['shop_mobile'] ?? '');

    if (empty($shop_name))    $errors[] = "শপের নাম দিন।";
    if (empty($shop_address)) $errors[] = "শপের ঠিকানা দিন।";
    if (!preg_match('/^[0-9+\-\s]{7,20}$/', $shop_mobile)) $errors[] = "সঠিক মোবাইল নম্বর দিন।";

    if (empty($errors)) {
        $stmt = $con->prepare("UPDATE shop_reg SET shop_name=?, shop_address=?, shop_mobile=? WHERE id=?");
        $stmt->bind_param("sssi", $shop_name, $shop_address, $shop_mobile, $up_id);
        if ($stmt->execute()) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            header("Location: shop_reg.php?msg=updated");
            exit();
        } else {
            $errors[] = "আপডেট ব্যর্থ হয়েছে।";
        }
    }
}

// ===================== LIST =====================
$shops = $con->query("SELECT * FROM shop_reg ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>শপ রেজিস্ট্রেশন</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/shop_reg.css">
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="container-fluid px-4 mt-4">
    <h3 class="page-title">🏪 শপ রেজিস্ট্রেশন</h3>

    <!-- সাকসেস মেসেজ -->
    <?php if (isset($_GET['msg'])): ?>
        <?php
        $msgs = [
            'added'   => ['success', '✅ শপ সফলভাবে যোগ হয়েছে!'],
            'updated' => ['success', '✅ শপ সফলভাবে আপডেট হয়েছে!'],
            'deleted' => ['danger',  '🗑️ শপ মুছে ফেলা হয়েছে!'],
        ];
        $m = $msgs[$_GET['msg']] ?? null;
        if ($m): ?>
            <div class="alert alert-<?= $m[0] ?> alert-dismissible fade show">
                <?= $m[1] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <!-- এরর -->
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $e): ?>
                    <li><?= htmlspecialchars($e) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <!-- ফর্ম: ADD / EDIT -->
    <div class="shop-card card">
        <div class="card-header <?= $editData ? 'edit-header' : 'add-header' ?>">
            <?= $editData ? '✏️ শপ এডিট করুন' : '➕ নতুন শপ যোগ করুন' ?>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                <input type="hidden" name="action"     value="<?= $editData ? 'update' : 'insert' ?>">
                <?php if ($editData): ?>
                    <input type="hidden" name="edit_id" value="<?= $editData['id'] ?>">
                <?php endif; ?>

                <div class="mb-3">
                    <label class="form-label">শপের নাম <span class="text-danger">*</span></label>
                    <input type="text" name="shop_name" maxlength="255"
                           value="<?= htmlspecialchars($editData['shop_name'] ?? ($_POST['shop_name'] ?? '')) ?>"
                           class="form-control" placeholder="শপের নাম লিখুন" required>
                </div>

                <div class="mb-3">
                    <label class="form-label">শপের ঠিকানা <span class="text-danger">*</span></label>
                    <textarea name="shop_address" maxlength="500" rows="2"
                              class="form-control"
                              placeholder="শপের ঠিকানা লিখুন" required><?= htmlspecialchars($editData['shop_address'] ?? ($_POST['shop_address'] ?? '')) ?></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label">শপের মোবাইল <span class="text-danger">*</span></label>
                    <input type="text" name="shop_mobile" maxlength="20"
                           value="<?= htmlspecialchars($editData['shop_mobile'] ?? ($_POST['shop_mobile'] ?? '')) ?>"
                           class="form-control" placeholder="01XXXXXXXXX" required>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn <?= $editData ? 'btn-update' : 'btn-add' ?>">
                        <?= $editData ? '✅ আপডেট করুন' : '➕ যোগ করুন' ?>
                    </button>
                    <?php if ($editData): ?>
                        <a href="shop_reg.php" class="btn btn-cancel">✖ বাতিল</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <!-- শপ লিস্ট -->
    <div class="shop-card card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table shop-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>শপের নাম</th>
                            <th>ঠিকানা</th>
                            <th>মোবাইল</th>
                            <th>তারিখ</th>
                            <th>কার্যক্রম</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($shops->num_rows === 0): ?>
                            <tr>
                                <td colspan="6" class="text-center empty-msg">কোনো শপ যোগ করা হয়নি।</td>
                            </tr>
                        <?php else: ?>
                            <?php while ($row = $shops->fetch_assoc()): ?>
                                <tr>
                                    <td><?= $row['id'] ?></td>
                                    <td class="shop-name-badge">🏪 <?= htmlspecialchars($row['shop_name']) ?></td>
                                    <td><?= htmlspecialchars($row['shop_address']) ?></td>
                                    <td>📞 <?= htmlspecialchars($row['shop_mobile']) ?></td>
                                    <td class="date-text"><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                                    <td>
                                        <a href="shop_reg.php?edit=<?= $row['id'] ?>"
                                           class="btn btn-edit">✏️ এডিট</a>
                                        <a href="shop_reg.php?delete=<?= $row['id'] ?>"
                                           class="btn btn-delete"
                                           onclick="return confirm('নিশ্চিতভাবে মুছতে চান?')">
                                           🗑️ ডিলিট
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div><!-- /.shop-container -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>