<?php
session_start();
include("layout.php");
include("db.php");

// Handle store operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_store':
                $store_name = $_POST['store_name'];
                $store_code = $_POST['store_code'];
                $address = $_POST['address'];
                $phone = $_POST['phone'];
                $email = $_POST['email'];
                $manager_name = $_POST['manager_name'];
                $branch_id = $_POST['branch_id'] ?? 1;
                
                $stmt = $conn->prepare("INSERT INTO stores (store_name, store_code, address, phone, email, manager_name, branch_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("ssssssi", $store_name, $store_code, $address, $phone, $email, $manager_name, $branch_id);
                $stmt->execute();
                $stmt->close();
                

                
                header("Location: store_management.php?success=1");
                exit;
                break;
                
            case 'update_store':
                $store_id = $_POST['store_id'];
                $store_name = $_POST['store_name'];
                $store_code = $_POST['store_code'];
                $address = $_POST['address'];
                $phone = $_POST['phone'];
                $email = $_POST['email'];
                $manager_name = $_POST['manager_name'];
                $branch_id = $_POST['branch_id'];
                $is_active = $_POST['is_active'];
                
                $stmt = $conn->prepare("UPDATE stores SET store_name=?, store_code=?, address=?, phone=?, email=?, manager_name=?, branch_id=?, is_active=? WHERE id=?");
                $stmt->bind_param("ssssssiii", $store_name, $store_code, $address, $phone, $email, $manager_name, $branch_id, $is_active, $store_id);
                $stmt->execute();
                $stmt->close();
                
                header("Location: store_management.php?success=2");
                exit;
                break;
                
            case 'set_default_store':
                $store_id = $_POST['store_id'];
                
                // First, remove default flag from all stores
                $conn->query("UPDATE stores SET is_default = 0");
                
                // Set the selected store as default
                $stmt = $conn->prepare("UPDATE stores SET is_default = 1 WHERE id = ?");
                $stmt->bind_param("i", $store_id);
                $stmt->execute();
                $stmt->close();
                
                // Update branch_info to link with this default store
                $stmt = $conn->prepare("UPDATE branch_info SET default_store_id = ? WHERE id = 1");
                $stmt->bind_param("i", $store_id);
                $stmt->execute();
                $stmt->close();
                
                header("Location: store_management.php?success=3");
                exit;
                break;
        }
    }
}

// Get stores list with branch information
$stores_query = "SELECT s.*, b.branch_name, 
                 CASE WHEN s.is_default = 1 THEN 'Default Store' ELSE 'Regular Store' END as store_type
                 FROM stores s 
                 LEFT JOIN branch_info b ON s.branch_id = b.id 
                 ORDER BY s.is_default DESC, s.store_name";
$stores_result = $conn->query($stores_query);
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>Store Management</h4>
                <h6>Manage multiple store locations</h6>
            </div>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addStoreModal">
                    <i class="fas fa-plus"></i> Add New Store
                </button>
            </div>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php 
                if ($_GET['success'] == 1) echo "Store added successfully!";
                elseif ($_GET['success'] == 2) echo "Store updated successfully!";
                elseif ($_GET['success'] == 3) echo "Default store set successfully!";
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Stores List -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table datanew">
                        <thead>
                            <tr>
                                <th>Store Name</th>
                                <th>Store Code</th>
                                <th>Branch</th>
                                <th>Manager</th>
                                <th>Contact</th>
                                <th>Status</th>
                                <th>Type</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($store = $stores_result->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="store-icon me-3">
                                                <i class="fas fa-store text-primary"></i>
                                            </div>
                                            <div>
                                                <h6 class="mb-0"><?= htmlspecialchars($store['store_name']) ?></h6>
                                                <small class="text-muted"><?= htmlspecialchars($store['address']) ?></small>
                                            </div>
                                        </div>
                                    </td>
                                    <td><span class="badge bg-secondary"><?= htmlspecialchars($store['store_code']) ?></span></td>
                                    <td><span class="badge bg-info"><?= htmlspecialchars($store['branch_name'] ?? 'No Branch') ?></span></td>
                                    <td><?= htmlspecialchars($store['manager_name']) ?></td>
                                    <td>
                                        <div>
                                            <div><?= htmlspecialchars($store['phone']) ?></div>
                                            <small class="text-muted"><?= htmlspecialchars($store['email']) ?></small>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($store['is_active']): ?>
                                            <span class="badge bg-success">Active</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($store['is_default']): ?>
                                            <span class="badge bg-warning text-dark">Default Store</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Regular Store</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-2">
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    onclick="editStore(<?= $store['id'] ?>, '<?= htmlspecialchars($store['store_name']) ?>', '<?= htmlspecialchars($store['store_code']) ?>', '<?= htmlspecialchars($store['address']) ?>', '<?= htmlspecialchars($store['phone']) ?>', '<?= htmlspecialchars($store['email']) ?>', '<?= htmlspecialchars($store['manager_name']) ?>', <?= $store['branch_id'] ?>, <?= $store['is_active'] ?>)">
                                                <i class="fas fa-edit"></i>
                                            </button>

                                            <?php if (!$store['is_default']): ?>
                                                <form method="POST" style="display: inline;" onsubmit="return confirm('Set <?= htmlspecialchars($store['store_name']) ?> as the default store?')">
                                                    <input type="hidden" name="action" value="set_default_store">
                                                    <input type="hidden" name="store_id" value="<?= $store['id'] ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-warning" title="Set as Default Store">
                                                        <i class="fas fa-star"></i>
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Store Modal -->
<div class="modal fade" id="addStoreModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Store</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add_store">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Store Name *</label>
                                <input type="text" name="store_name" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Store Code *</label>
                                <input type="text" name="store_code" class="form-control" required>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <textarea name="address" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Phone</label>
                                <input type="text" name="phone" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Email</label>
                                <input type="email" name="email" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Manager Name</label>
                                <input type="text" name="manager_name" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Branch *</label>
                                <select name="branch_id" class="form-control" required>
                                    <?php
                                    $branches = $conn->query("SELECT * FROM branch_info WHERE is_active = 1 ORDER BY branch_name");
                                    while ($branch = $branches->fetch_assoc()) {
                                        echo "<option value='{$branch['id']}'>{$branch['branch_name']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Store</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Store Modal -->
<div class="modal fade" id="editStoreModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Store</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_store">
                <input type="hidden" name="store_id" id="edit_store_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Store Name *</label>
                                <input type="text" name="store_name" id="edit_store_name" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Store Code *</label>
                                <input type="text" name="store_code" id="edit_store_code" class="form-control" required>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <textarea name="address" id="edit_address" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Phone</label>
                                <input type="text" name="phone" id="edit_phone" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Email</label>
                                <input type="email" name="email" id="edit_email" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Manager Name</label>
                                <input type="text" name="manager_name" id="edit_manager_name" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Branch *</label>
                                <select name="branch_id" id="edit_branch_id" class="form-control" required>
                                    <?php
                                    $branches = $conn->query("SELECT * FROM branch_info WHERE is_active = 1 ORDER BY branch_name");
                                    while ($branch = $branches->fetch_assoc()) {
                                        echo "<option value='{$branch['id']}'>{$branch['branch_name']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Status</label>
                                <select name="is_active" id="edit_is_active" class="form-control">
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Store</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editStore(id, name, code, address, phone, email, manager, branchId, active) {
    document.getElementById('edit_store_id').value = id;
    document.getElementById('edit_store_name').value = name;
    document.getElementById('edit_store_code').value = code;
    document.getElementById('edit_address').value = address;
    document.getElementById('edit_phone').value = phone;
    document.getElementById('edit_email').value = email;
    document.getElementById('edit_manager_name').value = manager;
    document.getElementById('edit_branch_id').value = branchId;
    document.getElementById('edit_is_active').value = active;
    
    new bootstrap.Modal(document.getElementById('editStoreModal')).show();
}
</script>
