<?php
require_once 'includes/db.php';
requireRole('owner');

$branches = fetchAll("SELECT * FROM branches WHERE company_id = ? ORDER BY created_at DESC", [$_SESSION['company_id']]);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save') {
        $name = $_POST['name'];
        $phone = $_POST['phone'];
        $address = $_POST['address'];
        $branch_id = $_POST['id'] ?? null;
        
        if ($branch_id) {
            query("UPDATE branches SET name = ?, phone = ?, address = ? WHERE id = ? AND company_id = ?", 
                  [$name, $phone, $address, $branch_id, $_SESSION['company_id']]);
            logAudit('BRANCH_UPDATE', "Updated branch: $name");
        } else {
            query("INSERT INTO branches (company_id, name, phone, address) VALUES (?, ?, ?, ?)", 
                  [$_SESSION['company_id'], $name, $phone, $address]);
            logAudit('BRANCH_CREATE', "Created new branch: $name");
        }
    } elseif ($_POST['action'] === 'delete') {
        $branch_id = $_POST['id'];
        query("DELETE FROM branches WHERE id = ? AND company_id = ?", [$branch_id, $_SESSION['company_id']]);
        logAudit('BRANCH_DELETE', "Deleted branch ID: $branch_id");
    }
    header("Location: " . url('branches'));
    exit;
}
?>

<div style="display: flex; justify-content: flex-end; align-items: center; margin-bottom: 2rem;">
    <button class="btn btn-primary" onclick="openAddBranchModal()">
        <i class="fas fa-plus"></i> Add New Branch
    </button>
</div>

<div class="data-grid">
    <?php foreach ($branches as $branch): ?>
    <div class="data-card">
        <div class="data-card-header">
            <div>
                <h3 style="font-size: 1.125rem; font-weight: 700; margin-bottom: 0.25rem;"><?php echo htmlspecialchars($branch['name']); ?></h3>
                <div style="font-size: 0.8rem; color: var(--text-muted);">ID: BRN-<?php echo str_pad($branch['id'], 3, '0', STR_PAD_LEFT); ?></div>
            </div>
            <div style="width: 40px; height: 40px; border-radius: 10px; background: rgba(99, 102, 241, 0.1); color: var(--primary); display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-location-dot"></i>
            </div>
        </div>
        
        <div class="data-card-body">
            <div class="data-card-item">
                <i class="fas fa-phone"></i>
                <span><?php echo htmlspecialchars($branch['phone'] ?? 'N/A'); ?></span>
            </div>
            <div class="data-card-item">
                <i class="fas fa-map-marker-alt"></i>
                <span><?php echo htmlspecialchars($branch['address'] ?? 'N/A'); ?></span>
            </div>
        </div>

        <div class="data-card-footer">
            <button class="btn" style="background: var(--bg-dark); padding: 0.5rem;" onclick='editBranch(<?php echo json_encode($branch); ?>)'>
                <i class="fas fa-edit"></i> Edit
            </button>
            <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); padding: 0.5rem;" onclick="deleteBranch(<?php echo $branch['id']; ?>)">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    </div>
    <?php endforeach; ?>

    <?php if (empty($branches)): ?>
    <div style="grid-column: 1 / -1; text-align: center; padding: 4rem; background: var(--bg-card); border-radius: 16px; border: 2px dashed var(--border);">
        <i class="fas fa-code-branch fa-3x" style="margin-bottom: 1.5rem; color: var(--text-muted); opacity: 0.5;"></i>
        <h3 style="color: var(--text-main); margin-bottom: 0.5rem;">No Branches Configured</h3>
        <p style="color: var(--text-muted);">Add your first branch or office location to get started.</p>
    </div>
    <?php endif; ?>
</div>

<!-- Branch Modal -->
<div id="branchModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Add New Branch</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('branchModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="branchForm" method="POST" action="">
            <input type="hidden" name="action" value="save">
            <input type="hidden" id="branch_id" name="id">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Branch Name <span class="required-mark">*</span></label>
                    <input type="text" id="branch_name" name="name" class="form-control" placeholder="e.g. Colombo Warehouse" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Phone Number <span class="required-mark">*</span></label>
                    <input type="tel" id="branch_phone" name="phone" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Address <span class="required-mark">*</span></label>
                    <textarea id="branch_address" name="address" class="form-control" rows="3" required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background: rgba(0,0,0,0.05);" onclick="closeModal('branchModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Branch</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddBranchModal() {
    document.getElementById('modalTitle').innerText = 'Add New Branch';
    document.getElementById('branchForm').reset();
    document.getElementById('branch_id').value = '';
    openModal('branchModal');
}

function editBranch(branch) {
    document.getElementById('modalTitle').innerText = 'Edit Branch';
    document.getElementById('branch_id').value = branch.id;
    document.getElementById('branch_name').value = branch.name;
    document.getElementById('branch_phone').value = branch.phone;
    document.getElementById('branch_address').value = branch.address;
    openModal('branchModal');
}

async function deleteBranch(id) {
    if (await confirmAction({ title: 'Delete Branch', message: 'Are you sure you want to delete this branch?' })) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>
