<?php
// branches.php
session_start();
require_once 'config/db_config.php';

// ---- Authentication and Authorization ----
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || !isset($_SESSION['owner_id'])) {
    header("Location: ../login.php");
    exit();
}

// Check if user has permission to view branches
$allowed_roles = ['super_admin', 'admin', 'branch', 'warehouse_manager'];
if (!in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../unauthorized.php");
    exit();
}

$owner_id = $_SESSION['owner_id'];
$role = $_SESSION['role'];

// ---- 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'); }

// ---- Filter Logic ----
$filter = $_GET['filter'] ?? 'all';
$allowed_filters = ['all', 'own', 'third_party'];
if (!in_array($filter, $allowed_filters)) {
    $filter = 'all';
}

// ---- Determine if user is super_admin ----
// In the simplified login system, all owners are super_admin for their own businesses
$is_super_admin = ($role === 'super_admin');

// ---- Build WHERE clause based on owner_id ----
$where = "WHERE b.owner_id = ?";
$params = [$owner_id];

if ($filter === 'own') {
    $where .= " AND b.third_party = 0";
} elseif ($filter === 'third_party') {
    $where .= " AND b.third_party = 1";
}

// Note: In the simplified system, super_admin only sees their own branches
// If you want super_admin to see all branches across all owners, you'll need
// to modify the database structure to have a separate admin role

// ---- Fetch branches with owner information ----
try {
    $sql = "
        SELECT 
            b.branch_id, 
            b.branch_name, 
            b.address, 
            b.city, 
            b.state, 
            b.country, 
            b.image_url, 
            b.created_at, 
            b.third_party,
            b.owner_id,
            o.owner_name,
            o.business_name
        FROM branches b
        LEFT JOIN owners o ON b.owner_id = o.owner_id
        $where
        ORDER BY b.created_at DESC, b.branch_id DESC
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $branches = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching branches: " . h($e->getMessage());
    $branches = [];
}

// ---- Count totals for filter labels ----
try {
    // All branches count for current owner
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM branches WHERE owner_id = ?");
    $stmt->execute([$owner_id]);
    $count_all = $stmt->fetchColumn();
    
    // Own branches count (non-third-party)
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM branches WHERE owner_id = ? AND third_party = 0");
    $stmt->execute([$owner_id]);
    $count_own = $stmt->fetchColumn();
    
    // Third-party branches count
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM branches WHERE owner_id = ? AND third_party = 1");
    $stmt->execute([$owner_id]);
    $count_third_party = $stmt->fetchColumn();
    
    $counts = [
        'all' => $count_all,
        'own' => $count_own,
        'third_party' => $count_third_party,
    ];
} catch (PDOException $e) {
    $counts = ['all' => 0, 'own' => 0, 'third_party' => 0];
}

// ---- Check if user can create branches ----
$can_create_branch = in_array($role, ['super_admin', 'admin']);

// ---- DataTable init script ----
$script = '
<script>
document.addEventListener("DOMContentLoaded", function () {
    let table = null;
    function initDataTable() {
        if (table) table.destroy();
        try {
            table = new DataTable("#branchesTable", {
                responsive: true,
                pageLength: 10,
                language: {
                    search: "_INPUT_",
                    searchPlaceholder: "Search branches..."
                },
                columnDefs: [
                    { orderable: false, targets: [0, 7, 8, 9] }
                ]
            });
        } catch (e) {
            console.error("DataTable init error:", e);
        }
    }
    initDataTable();

    // Re-init on filter change
    document.getElementById("branchFilter").addEventListener("change", function() {
        this.form.submit();
    });

    // Select/Deselect all
    const selectAllCheckbox = document.getElementById("selectAll");
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener("change", function() {
            const checkboxes = document.querySelectorAll("input[name=\"branch_ids[]\"]");
            checkboxes.forEach(cb => cb.checked = this.checked);
        });
    }
});

function confirmDelete(branchId, branchName, ownerId) {
    // Check if user is trying to delete their own branch
    const currentOwnerId = ' . $owner_id . ';
    if (ownerId != currentOwnerId) {
        alert("You can only delete your own branches.");
        return;
    }
    
    document.getElementById("branchName").textContent = branchName;
    document.getElementById("deleteBranchId").value = branchId;
    new bootstrap.Modal(document.getElementById("deleteModal")).show();
}
</script>';
?>

<?php include './partials/layouts/layoutTop.php'; ?>

<!-- Font Awesome 6 CDN (Free) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<style>
    .filter-form { display: inline-block; }
    .filter-select { min-width: 180px; }
    .badge-third-party {
        background-color: #fd7e14;
        color: white;
        font-size: 0.65rem;
        padding: 2px 6px;
        border-radius: 4px;
        margin-left: 6px;
        vertical-align: middle;
    }
    .badge-owner {
        background-color: #6f42c1;
        color: white;
        font-size: 0.65rem;
        padding: 2px 6px;
        border-radius: 4px;
        margin-left: 4px;
    }
    .branch-card .badge-third-party { font-size: 0.6rem; }
    .fa-icon { font-size: 0.9rem; margin-right: 4px; }
    .action-btn {
        width: 32px; height: 32px;
        display: inline-flex; align-items: center; justify-content: center;
        border-radius: 50%; font-size: 0.85rem;
    }
    .owner-info {
        font-size: 0.8rem;
        color: #6c757d;
    }
    .disabled-btn {
        opacity: 0.6;
        cursor: not-allowed;
    }
    @media (max-width: 768px) {
        .filter-form, .filter-select { width: 100%; }
        .action-btn { width: 36px; height: 36px; }
    }
</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">My Branches</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">
                    <i class="fa-solid fa-house fa-icon"></i> Dashboard
                </a>
            </li>
            <li>-</li>
            <li class="fw-medium">Branches</li>
        </ul>
    </div>

    <!-- Success/Error Messages -->
    <?php if (!empty($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show mb-24" role="alert">
            <?= h($_SESSION['success']); unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if (!empty($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show mb-24" role="alert">
            <?= h($_SESSION['error']); unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['updated'])): ?>
        <div class="alert alert-success alert-dismissible fade show mb-24" role="alert">Branch updated successfully!</div>
    <?php endif; ?>
    <?php if (isset($_GET['created'])): ?>
        <div class="alert alert-success alert-dismissible fade show mb-24" role="alert">Branch created successfully!</div>
    <?php endif; ?>
    <?php if (isset($_GET['deleted'])): ?>
        <div class="alert alert-success alert-dismissible fade show mb-24" role="alert">Branch deleted successfully!</div>
    <?php endif; ?>

    <div class="card basic-data-table">
        <div class="card-header">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                <div class="d-flex align-items-center gap-3 flex-wrap">
                    <h5 class="card-title mb-0">My Branches (<?= count($branches) ?>)</h5>

                    <!-- Filter Form -->
                    <form method="GET" class="filter-form">
                        <div class="input-group input-group-sm">
                            <span class="input-group-text bg-white border-end-0">
                                <i class="fa-solid fa-filter text-muted"></i>
                            </span>
                            <select name="filter" id="branchFilter" class="form-select form-select-sm filter-select border-start-0" onchange="this.form.submit()">
                                <option value="all" <?= $filter === 'all' ? 'selected' : '' ?>>
                                    All (<?= $counts['all'] ?>)
                                </option>
                                <option value="own" <?= $filter === 'own' ? 'selected' : '' ?>>
                                    Own (<?= $counts['own'] ?>)
                                </option>
                                <option value="third_party" <?= $filter === 'third_party' ? 'selected' : '' ?>>
                                    Third Party (<?= $counts['third_party'] ?>)
                                </option>
                            </select>
                        </div>
                    </form>
                </div>

                <?php if ($can_create_branch): ?>
                    <a href="create_branch.php" class="btn btn-primary btn-sm bg-primary-600 hover-bg-primary-700 text-white">
                        <i class="fa-solid fa-plus fa-icon"></i> Create New Branch
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="card-body">
            <!-- Desktop Table View -->
            <div class="d-none d-lg-block">
                <div class="table-responsive">
                    <table class="table bordered-table mb-0" id="branchesTable">
                        <thead>
                            <tr>
                                <th>
                                    <div class="form-check style-check d-flex align-items-center">
                                        <input class="form-check-input" type="checkbox" id="selectAll">
                                        <label class="form-check-label">S.L</label>
                                    </div>
                                </th>
                                <th>Branch Name</th>
                                <th>Address</th>
                                <th>City</th>
                                <th>State</th>
                                <th>Country</th>
                                <th>Image</th>
                                <th>Type</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                           
                                <?php foreach ($branches as $index => $branch): 
                                    $is_my_branch = ($branch['owner_id'] ?? 0) == $owner_id;
                                    $can_edit = $is_my_branch && in_array($role, ['super_admin', 'admin']);
                                    $can_delete = $is_my_branch && in_array($role, ['super_admin', 'admin']);
                                ?>
                                    <tr>
                                        <td>
                                            <div class="form-check style-check d-flex align-items-center">
                                                <input class="form-check-input" type="checkbox" name="branch_ids[]" value="<?= h($branch['branch_id']); ?>">
                                                <label class="form-check-label"><?= sprintf('%02d', $index + 1); ?></label>
                                            </div>
                                        </td>
                                        <td>
                                            <a href="view_branch.php?id=<?= (int)$branch['branch_id']; ?>" class="text-primary-600">
                                                <i class="fa-solid fa-store fa-icon"></i>
                                                <?= h($branch['branch_name']); ?>
                                            </a>
                                        </td>
                                        <td><?= h($branch['address'] ?? 'N/A'); ?></td>
                                        <td><?= h($branch['city'] ?? 'N/A'); ?></td>
                                        <td><?= h($branch['state'] ?? 'N/A'); ?></td>
                                        <td><?= h($branch['country'] ?? 'N/A'); ?></td>
                                        <td>
                                            <?php if (!empty($branch['image_url'])): ?>
                                                <img src="<?= h($branch['image_url']); ?>" alt="<?= h($branch['branch_name']); ?>"
                                                     class="rounded" style="width:40px;height:40px;object-fit:cover;">
                                            <?php else: ?>
                                                <i class="fa-regular fa-image text-muted"></i>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($branch['third_party']): ?>
                                                <span class="badge-third-party">3rd Party</span>
                                            <?php else: ?>
                                                <span class="badge bg-primary" style="font-size:0.65rem; padding:2px 6px;">Own</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-sm">
                                            <?= date('M d, Y', strtotime($branch['created_at'] ?? '')); ?>
                                        </td>
                                        <td>
                                            <div class="d-flex gap-1">
                                                <a href="view_branch.php?id=<?= (int)$branch['branch_id']; ?>"
                                                   class="action-btn bg-primary-light text-primary-600" title="View">
                                                    <i class="fa-solid fa-eye"></i>
                                                </a>
                                                
                                                <?php if ($can_edit): ?>
                                                    <a href="edit_branch.php?id=<?= (int)$branch['branch_id']; ?>"
                                                       class="action-btn bg-success-focus text-success-main" title="Edit">
                                                        <i class="fa-solid fa-pen-to-square"></i>
                                                    </a>
                                                <?php else: ?>
                                                    <span class="action-btn bg-secondary text-white disabled-btn" title="Cannot edit">
                                                        <i class="fa-solid fa-pen-to-square"></i>
                                                    </span>
                                                <?php endif; ?>
                                                
                                                <?php if ($can_delete): ?>
                                                    <button type="button"
                                                            class="action-btn bg-danger-focus text-danger-main border-0"
                                                            onclick="confirmDelete(<?= (int)$branch['branch_id']; ?>, '<?= h(addslashes($branch['branch_name'])); ?>', <?= $branch['owner_id'] ?? 0 ?>)"
                                                            title="Delete">
                                                        <i class="fa-solid fa-trash"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <span class="action-btn bg-secondary text-white disabled-btn" title="Cannot delete">
                                                        <i class="fa-solid fa-trash"></i>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                           
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Mobile Card View -->
            <div class="d-block d-lg-none">
                <?php if (empty($branches)): ?>
                    <div class="text-center py-5">
                        <i class="fa-solid fa-store fa-3x text-secondary mb-3 d-block"></i>
                        <span class="text-muted">No branches found</span>
                    </div>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($branches as $index => $branch): 
                            $is_my_branch = ($branch['owner_id'] ?? 0) == $owner_id;
                            $can_edit = $is_my_branch && in_array($role, ['super_admin', 'admin']);
                            $can_delete = $is_my_branch && in_array($role, ['super_admin', 'admin']);
                        ?>
                            <div class="col-12">
                                <div class="card branch-card shadow-sm">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div>
                                                <h6 class="card-title mb-0 text-sm fw-bold">
                                                    <i class="fa-solid fa-store fa-icon"></i>
                                                    <?= h($branch['branch_name']); ?>
                                                </h6>
                                            </div>
                                            <div class="d-flex flex-column align-items-end gap-1">
                                                <div class="form-check style-check">
                                                    <input class="form-check-input" type="checkbox" name="branch_ids[]" value="<?= h($branch['branch_id']); ?>">
                                                    <label class="form-check-label text-sm">S.L: <?= sprintf('%02d', $index + 1); ?></label>
                                                </div>
                                                <?php if ($branch['third_party']): ?>
                                                    <span class="badge-third-party">3rd Party</span>
                                                <?php else: ?>
                                                    <span class="badge bg-primary" style="font-size:0.6rem; padding:2px 6px;">Own</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="mb-2">
                                            <p class="text-sm mb-1"><strong><i class="fa-solid fa-location-dot fa-icon"></i> Address:</strong> <?= h($branch['address'] ?? 'N/A'); ?></p>
                                            <p class="text-sm mb-1"><strong><i class="fa-solid fa-city fa-icon"></i> City:</strong> <?= h($branch['city'] ?? 'N/A'); ?></p>
                                            <p class="text-sm mb-1"><strong><i class="fa-solid fa-flag fa-icon"></i> State:</strong> <?= h($branch['state'] ?? 'N/A'); ?></p>
                                            <p class="text-sm mb-1"><strong><i class="fa-solid fa-earth-asia fa-icon"></i> Country:</strong> <?= h($branch['country'] ?? 'N/A'); ?></p>
                                            <p class="text-sm mb-1"><strong><i class="fa-solid fa-calendar fa-icon"></i> Created:</strong> <?= date('M d, Y', strtotime($branch['created_at'] ?? '')); ?></p>
                                        </div>
                                        <div class="mb-2">
                                            <?php if (!empty($branch['image_url'])): ?>
                                                <img src="<?= h($branch['image_url']); ?>" alt="<?= h($branch['branch_name']); ?>" class="img-thumbnail" style="width:60px;height:60px;">
                                            <?php else: ?>
                                                <p class="text-sm text-muted mb-1"><i class="fa-regular fa-image fa-icon"></i> No Image</p>
                                            <?php endif; ?>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center mt-3 gap-2">
                                            <div class="d-flex gap-2 flex-wrap">
                                                <a href="view_branch.php?id=<?= (int)$branch['branch_id']; ?>" class="btn btn-sm btn-outline-primary">
                                                    <i class="fa-solid fa-eye fa-icon"></i> View
                                                </a>
                                                
                                                <?php if ($can_edit): ?>
                                                    <a href="edit_branch.php?id=<?= (int)$branch['branch_id']; ?>" class="btn btn-sm btn-outline-success">
                                                        <i class="fa-solid fa-pen-to-square fa-icon"></i> Edit
                                                    </a>
                                                <?php else: ?>
                                                    <button class="btn btn-sm btn-outline-secondary disabled" disabled>
                                                        <i class="fa-solid fa-pen-to-square fa-icon"></i> Edit
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if ($can_delete): ?>
                                                <button type="button" class="btn btn-sm btn-outline-danger"
                                                        onclick="confirmDelete(<?= (int)$branch['branch_id']; ?>, '<?= h(addslashes($branch['branch_name'])); ?>', <?= $branch['owner_id'] ?? 0 ?>)">
                                                    <i class="fa-solid fa-trash fa-icon"></i> Delete
                                                </button>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-outline-secondary disabled" disabled>
                                                    <i class="fa-solid fa-trash fa-icon"></i> Delete
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fa-solid fa-triangle-exclamation text-danger me-2"></i> Confirm Delete
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete branch "<span id="branchName" class="fw-bold"></span>"?</p>
                <p class="text-danger small">This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">
                    <i class="fa-solid fa-ban"></i> Cancel
                </button>
                <form id="deleteForm" method="POST" action="delete_branch.php" class="d-inline">
                    <input type="hidden" name="branch_id" id="deleteBranchId">
                    <input type="hidden" name="csrf" value="<?= h($csrf); ?>">
                    <button type="submit" class="btn btn-danger btn-sm">
                        <i class="fa-solid fa-trash"></i> Delete
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include './partials/layouts/layoutBottom.php'; ?>