<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');

$sql = "SELECT * FROM stores ORDER BY created_at DESC";
$stores = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Store Management - Digital POS</title>
    <link rel="stylesheet" href="../../css/dashboard.css">
    <style>
        body, html {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            min-height: 100vh;
            overflow-x: hidden;
        }

        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }

        .content {
            margin: 100px auto 40px auto;
            padding: 30px 40px;
            max-width: 1200px;
            backdrop-filter: blur(15px);
            background: rgba(255, 255, 255, 0.08);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
        }

        h2 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 1.8rem;
        }

        .user-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 12px;
        }

        .user-controls input[type="text"] {
            padding: 10px;
            width: 280px;
            border-radius: 10px;
            border: none;
            outline: none;
            background: rgba(255,255,255,0.1);
            color: white;
            box-shadow: inset 0 0 5px rgba(255,255,255,0.2);
        }

        .add-user {
            background: #ff6f00;
            color: white;
            padding: 10px 18px;
            border: none;
            border-radius: 25px;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.3s;
        }

        .add-user:hover {
            background: #e65c00;
        }

        .user-table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(0,0,0,0.3);
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 12px rgba(0,0,0,0.6);
        }

        .user-table th, .user-table td {
            padding: 14px 16px;
            text-align: left;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            font-size: 0.95rem;
        }

        .user-table th {
            background: rgba(255,111,0,0.9);
        }

        .actions button {
            margin-right: 5px;
            padding: 6px 12px;
            font-size: 13px;
            cursor: pointer;
            border: none;
            border-radius: 6px;
            transition: background 0.3s ease;
        }

        .actions .edit {
            background-color: #66b2ff;
            color: white;
        }

        .actions .edit:hover {
            background-color: #3399ff;
        }

        .actions .delete {
            background-color: #ff4d4d;
            color: white;
        }

        .actions .delete:hover {
            background-color: #e60000;
        }

        @media (max-width: 768px) {
            .user-controls {
                flex-direction: column;
                align-items: flex-start;
            }

            .user-controls input[type="text"] {
                width: 100%;
            }

            .user-table th, .user-table td {
                font-size: 13px;
                padding: 10px;
            }
        }

        #toast {
            position: fixed;
            top: 20px;
            right: 20px;
            min-width: 240px;
            padding: 12px 20px;
            border-radius: 8px;
            font-weight: bold;
            box-shadow: 0 4px 8px rgba(0,0,0,0.4);
            display: none;
            z-index: 999;
        }

        #toast.success { background: #4caf50; color: white; }
        #toast.error { background: #f44336; color: white; }
    </style>
</head>
<body>

<div class="overlay"></div>
<div id="toast"></div>

<div class="content">
    <h2>Store Management</h2>

    <div class="user-controls">
        <input type="text" id="searchInput" placeholder="Search by name, location or contact...">
        <button class="add-user" onclick="location.href='add_store.php'">Add New Store</button>
    </div>

    <table class="user-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>Store Name</th>
            <th>Address</th>
            <th>Contact</th>
            <th>Location</th>
            <th>Email</th>
            <th>T-PIN</th>
            <th>Created</th>
            <th>Actions</th>
        </tr>
        </thead>
        <tbody id="storeTableBody">
        <?php if ($stores && $stores->num_rows > 0): ?>
            <?php while ($row = $stores->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['store_name']) ?></td>
                    <td><?= htmlspecialchars($row['store_address']) ?></td>
                    <td><?= htmlspecialchars($row['store_contact']) ?></td>
                    <td><?= htmlspecialchars($row['location']) ?></td>
                    <td><?= htmlspecialchars($row['email']) ?></td>
                    <td><?= htmlspecialchars($row['t_pin']) ?></td>
                    <td><?= date("d M Y", strtotime($row['created_at'])) ?></td>
                    <td class="actions">
                        <button class="edit" onclick="editStore(<?= $row['id'] ?>)">Edit</button>
                        <button class="delete" onclick="deleteStore(<?= $row['id'] ?>)">Delete</button>
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="9">No stores found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<?php include('../../includes/footer.php'); ?>

<script>
    document.getElementById('searchInput').addEventListener('keyup', function () {
        const filter = this.value.toLowerCase();
        const rows = document.querySelectorAll('#storeTableBody tr');
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(filter) ? '' : 'none';
        });
    });

    function editStore(id) {
        window.location.href = `edit_store.php?id=${id}`;
    }

    function deleteStore(id) {
        if (confirm("Are you sure you want to delete this store?")) {
            const btn = document.querySelector(`button.delete[onclick="deleteStore(${id})"]`);
            btn.disabled = true;

            fetch('delete_store.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `id=${id}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showToast("✅ Store deleted successfully.", 'success');
                    btn.closest('tr').remove();
                } else {
                    showToast("❌ Failed: " + data.message, 'error');
                    btn.disabled = false;
                }
            })
            .catch(err => {
                console.error("Delete Error:", err);
                showToast("❌ Network error occurred.", 'error');
                btn.disabled = false;
            });
        }
    }

    function showToast(message, type='success') {
        const toast = document.getElementById('toast');
        toast.className = type;
        toast.innerText = message;
        toast.style.display = 'block';
        setTimeout(() => { toast.style.display = 'none'; }, 3500);
    }
</script>

</body>
</html>
