<?php
session_start();
require_once '../config/database.php';
require_once '../includes/branch_helper.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

ensure_school_branches_schema($pdo);

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_branch'])) {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['branch_name'] ?? '');
    $code = strtoupper(trim($_POST['branch_code'] ?? ''));
    $address = trim($_POST['address'] ?? '');
    $status = ($_POST['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active';

    if ($name === '' || $code === '') {
        $error = 'শাখার নাম ও কোড প্রয়োজন';
    } elseif (!preg_match('/^[A-Z0-9_-]{2,20}$/', $code)) {
        $error = 'কোড ২–২০ অক্ষর, শুধু A-Z, 0-9, _ বা -';
    } else {
        try {
            if ($id > 0) {
                $dup = $pdo->prepare('SELECT id FROM school_branches WHERE branch_code = ? AND id != ? LIMIT 1');
                $dup->execute([$code, $id]);
                if ($dup->fetch()) {
                    throw new Exception('এই কোড অন্য শাখায় ব্যবহৃত');
                }
                $stmt = $pdo->prepare('UPDATE school_branches SET branch_name = ?, branch_code = ?, address = ?, status = ? WHERE id = ?');
                $stmt->execute([$name, $code, $address ?: null, $status, $id]);
                $success = 'শাখা আপডেট হয়েছে';
            } else {
                $stmt = $pdo->prepare('INSERT INTO school_branches (branch_name, branch_code, address, status) VALUES (?, ?, ?, ?)');
                $stmt->execute([$name, $code, $address ?: null, $status]);
                $success = 'নতুন শাখা যোগ হয়েছে';
            }
        } catch (Exception $e) {
            $error = strpos($e->getMessage(), 'Duplicate') !== false
                ? 'এই কোড ইতিমধ্যে আছে'
                : 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $bid = (int)$_POST['delete_id'];
    try {
        $used = $pdo->prepare('SELECT COUNT(*) FROM students WHERE branch_id = ?');
        $used->execute([$bid]);
        if ((int)$used->fetchColumn() > 0) {
            $error = 'এই শাখায় শিক্ষার্থী আছে — মুছা যাবে না। inactive করুন।';
        } else {
            $pdo->prepare('DELETE FROM school_branches WHERE id = ?')->execute([$bid]);
            $success = 'শাখা মুছে ফেলা হয়েছে';
        }
    } catch (Exception $e) {
        $error = 'মুছতে সমস্যা: ' . $e->getMessage();
    }
}

$branches = $pdo->query("
    SELECT b.*, (SELECT COUNT(*) FROM students s WHERE s.branch_id = b.id AND s.status = 'active') AS student_count
    FROM school_branches b
    ORDER BY b.branch_name
")->fetchAll(PDO::FETCH_ASSOC);

$total_branches = count($branches);
$active_count = 0;
$inactive_count = 0;
$total_students = 0;
foreach ($branches as $b) {
    if (($b['status'] ?? '') === 'active') {
        $active_count++;
    } else {
        $inactive_count++;
    }
    $total_students += (int)($b['student_count'] ?? 0);
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শাখা ম্যানেজমেন্ট - স্কুল ম্যানেজমেন্ট</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root{--indigo:#4fc3f7;--teal:#4dd0e1;--purple:#b39ddb}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0;font-size:.82rem}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 20px rgba(0,0,0,.4);flex-wrap:wrap;gap:8px}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none;display:flex;align-items:center;gap:8px}
        .top-bar .nav-links{display:flex;gap:8px;flex-wrap:wrap}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.72rem;font-weight:500;padding:4px 10px;border-radius:6px;transition:.2s}
        .top-bar .nav-links a:hover,.top-bar .nav-links a.on{color:#fff;background:rgba(255,255,255,.1)}
        .page-head{padding:10px 0 8px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}
        .page-head h4{margin:0;font-size:1rem;font-weight:800;color:var(--purple)}
        .page-head p{margin:0;font-size:.7rem;color:rgba(255,255,255,.45)}
        .badge-count{background:rgba(179,157,219,.2);color:#ce93d8;font-size:.68rem;padding:2px 8px;border-radius:10px;font-weight:700}
        .stat-row{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:10px}
        .stat-card{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;display:flex;align-items:center;gap:8px}
        .stat-card .ic{width:32px;height:32px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:.9rem;flex-shrink:0}
        .stat-card .num{font-size:.9rem;font-weight:800;color:#fff;line-height:1.1}
        .stat-card .lbl{font-size:.66rem;color:rgba(255,255,255,.45)}
        .layout{display:grid;grid-template-columns:300px 1fr;gap:10px;align-items:start}
        .panel{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);border-radius:10px}
        .panel-hd{padding:8px 12px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;align-items:center;justify-content:space-between}
        .panel-hd h5{margin:0;font-size:.8rem;font-weight:700;color:#90caf9}
        .panel-bd{padding:10px 12px}
        .form-label{font-size:.7rem;font-weight:600;color:#90caf9;margin-bottom:2px}
        .form-control,.form-select{font-size:.76rem;padding:4px 8px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .form-control:focus,.form-select:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.12);color:#e0e0e0;background:rgba(0,0,0,.45)}
        .form-select option{background:#11294a;color:#e0e0e0}
        .form-control::placeholder{color:rgba(255,255,255,.3)}
        .form-hint{font-size:.64rem;color:rgba(255,255,255,.35);margin-top:2px}
        .btn-row{display:flex;gap:6px;margin-top:8px}
        .btn-xs{font-size:.72rem;padding:5px 12px;border-radius:6px;font-weight:600;border:none}
        .btn-save{background:linear-gradient(135deg,#1565c0,#1e88e5);color:#fff}
        .btn-save:hover{opacity:.92;color:#fff}
        .btn-reset{background:rgba(255,255,255,.08);color:rgba(255,255,255,.7);border:1px solid rgba(255,255,255,.12)}
        .alert-compact{font-size:.76rem;border-radius:8px;padding:6px 10px;margin-bottom:8px}
        .alert-success{background:rgba(46,125,50,.2);border:1px solid rgba(46,125,50,.3);color:#a5d6a7}
        .alert-danger{background:rgba(198,40,40,.2);border:1px solid rgba(198,40,40,.3);color:#ef9a9a}
        .table-wrap{max-height:calc(100vh - 240px);overflow:auto}
        .data-table{width:100%;border-collapse:collapse;font-size:.74rem}
        .data-table thead th{position:sticky;top:0;z-index:2;background:linear-gradient(135deg,#4527a0,#5e35b1);color:#fff;font-weight:600;padding:6px 8px;white-space:nowrap;border:none}
        .data-table tbody td{padding:5px 8px;border-bottom:1px solid rgba(255,255,255,.05);vertical-align:middle}
        .data-table tbody tr:hover{background:rgba(179,157,219,.08)}
        .data-table .name{font-weight:600;color:#fff}
        .data-table .muted{color:rgba(255,255,255,.42);font-size:.66rem}
        .code-pill{font-size:.66rem;padding:2px 7px;border-radius:5px;background:rgba(79,195,247,.12);color:#4fc3f7;font-weight:700}
        .badge-on{background:rgba(102,187,106,.15);color:#81c784;font-size:.62rem;padding:2px 7px;border-radius:8px;font-weight:700}
        .badge-off{background:rgba(255,255,255,.08);color:rgba(255,255,255,.45);font-size:.62rem;padding:2px 7px;border-radius:8px;font-weight:700}
        .act-btns{display:flex;gap:4px}
        .btn-icon{width:26px;height:26px;padding:0;border-radius:5px;font-size:.7rem;display:inline-flex;align-items:center;justify-content:center;border:1px solid transparent;cursor:pointer}
        .btn-edit{background:rgba(79,195,247,.12);border-color:rgba(79,195,247,.3);color:#4fc3f7}
        .btn-edit:hover{background:rgba(79,195,247,.22);color:#fff}
        .btn-del{background:rgba(239,83,80,.1);border-color:rgba(239,83,80,.3);color:#ef5350}
        .btn-del:hover:not(:disabled){background:rgba(239,83,80,.2);color:#fff}
        .btn-del:disabled{opacity:.35;cursor:not-allowed}
        .panel-ft{padding:6px 12px;border-top:1px solid rgba(255,255,255,.06);font-size:.66rem;color:rgba(255,255,255,.4)}
        .empty-state{text-align:center;padding:24px 10px;color:rgba(255,255,255,.35)}
        .empty-state i{font-size:1.6rem;margin-bottom:6px;display:block;color:rgba(179,157,219,.4)}
        @media(max-width:992px){
            .stat-row{grid-template-columns:repeat(2,1fr)}
            .layout{grid-template-columns:1fr}
            .table-wrap{max-height:none}
        }
        @media(max-width:576px){
            .data-table thead{display:none}
            .data-table tbody tr{display:block;margin-bottom:8px;padding:8px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:8px}
            .data-table tbody td{display:flex;justify-content:space-between;padding:3px 0;border:none}
            .data-table tbody td::before{content:attr(data-label);color:rgba(255,255,255,.4);font-size:.66rem}
            .data-table tbody td:last-child{justify-content:flex-end;padding-top:6px}
        }
    </style>
</head>
<body>
    <div class="top-bar">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a href="sessions.php"><i class="fas fa-calendar"></i> সেশন</a>
            <a href="branches.php" class="on"><i class="fas fa-code-branch"></i> শাখা</a>
            <a href="../students/add.php"><i class="fas fa-user-plus"></i> ছাত্র যোগ</a>
            <a href="settings.php"><i class="fas fa-cog"></i> সেটিংস</a>
            <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>

    <div class="container-fluid px-3 px-md-4 pb-3">
        <div class="page-head">
            <div>
                <h4><i class="fas fa-code-branch me-1"></i> শাখা ম্যানেজমেন্ট</h4>
                <p>শাখা যোগ, এডিট ও স্ট্যাটাস ব্যবস্থাপনা</p>
            </div>
            <span class="badge-count"><?= $total_branches ?> টি শাখা</span>
        </div>

        <?php if ($success): ?><div class="alert-compact alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>
        <?php if ($error): ?><div class="alert-compact alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

        <div class="stat-row">
            <div class="stat-card">
                <div class="ic" style="background:rgba(179,157,219,.15);color:#b39ddb"><i class="fas fa-code-branch"></i></div>
                <div><div class="num"><?= $total_branches ?></div><div class="lbl">মোট শাখা</div></div>
            </div>
            <div class="stat-card">
                <div class="ic" style="background:rgba(102,187,106,.12);color:#66bb6a"><i class="fas fa-check-circle"></i></div>
                <div><div class="num"><?= $active_count ?></div><div class="lbl">সক্রিয়</div></div>
            </div>
            <div class="stat-card">
                <div class="ic" style="background:rgba(255,255,255,.06);color:rgba(255,255,255,.5)"><i class="fas fa-pause-circle"></i></div>
                <div><div class="num"><?= $inactive_count ?></div><div class="lbl">নিষ্ক্রিয়</div></div>
            </div>
            <div class="stat-card">
                <div class="ic" style="background:rgba(79,195,247,.12);color:#4fc3f7"><i class="fas fa-users"></i></div>
                <div><div class="num"><?= $total_students ?></div><div class="lbl">শিক্ষার্থী</div></div>
            </div>
        </div>

        <div class="layout">
            <div class="panel">
                <div class="panel-hd"><h5><i class="fas fa-plus-circle me-1" style="color:var(--teal)"></i>নতুন / এডিট</h5></div>
                <div class="panel-bd">
                    <form method="post" id="branchForm">
                        <input type="hidden" name="id" id="id">
                        <div class="mb-2">
                            <label class="form-label">শাখার নাম *</label>
                            <input class="form-control" name="branch_name" id="branch_name" placeholder="মূল শাখা" required>
                        </div>
                        <div class="mb-2">
                            <label class="form-label">কোড *</label>
                            <input class="form-control text-uppercase" name="branch_code" id="branch_code" placeholder="MAIN" maxlength="20" required>
                            <div class="form-hint">যেমন MAIN, NORTH</div>
                        </div>
                        <div class="mb-2">
                            <label class="form-label">ঠিকানা</label>
                            <textarea class="form-control" name="address" id="address" rows="2" placeholder="ঐচ্ছিক"></textarea>
                        </div>
                        <div class="mb-1">
                            <label class="form-label">স্ট্যাটাস</label>
                            <select class="form-select" name="status" id="status">
                                <option value="active">সক্রিয়</option>
                                <option value="inactive">নিষ্ক্রিয়</option>
                            </select>
                        </div>
                        <div class="btn-row">
                            <button class="btn btn-xs btn-save" name="save_branch"><i class="fas fa-save me-1"></i>সংরক্ষণ</button>
                            <button class="btn btn-xs btn-reset" type="button" onclick="resetForm()"><i class="fas fa-eraser"></i></button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="panel">
                <div class="panel-hd">
                    <h5><i class="fas fa-list me-1" style="color:var(--indigo)"></i>শাখা তালিকা</h5>
                </div>
                <div class="table-wrap">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>নাম</th>
                                <th>কোড</th>
                                <th>ছাত্র</th>
                                <th>স্ট্যাটাস</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($branches)): ?>
                                <tr><td colspan="5">
                                    <div class="empty-state"><i class="fas fa-code-branch"></i>কোনো শাখা নেই — বামে ফর্ম থেকে যোগ করুন</div>
                                </td></tr>
                            <?php else: foreach ($branches as $b): ?>
                                <tr>
                                    <td data-label="নাম">
                                        <div class="name"><?= htmlspecialchars($b['branch_name']) ?></div>
                                        <?php if (!empty($b['address'])): ?>
                                            <div class="muted"><?= htmlspecialchars($b['address']) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td data-label="কোড"><span class="code-pill"><?= htmlspecialchars($b['branch_code']) ?></span></td>
                                    <td data-label="ছাত্র"><?= (int)$b['student_count'] ?> জন</td>
                                    <td data-label="স্ট্যাটাস">
                                        <span class="<?= $b['status'] === 'active' ? 'badge-on' : 'badge-off' ?>">
                                            <?= $b['status'] === 'active' ? 'সক্রিয়' : 'নিষ্ক্রিয়' ?>
                                        </span>
                                    </td>
                                    <td data-label="">
                                        <div class="act-btns">
                                            <button type="button" class="btn-icon btn-edit" title="এডিট" onclick='editRow(<?= json_encode($b, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>)'>
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="post" class="d-inline" onsubmit="return confirm('এই শাখা মুছতে চান?');">
                                                <input type="hidden" name="delete_id" value="<?= (int)$b['id'] ?>">
                                                <button type="submit" class="btn-icon btn-del" title="মুছুন" <?= (int)$b['student_count'] > 0 ? 'disabled' : '' ?>>
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
                <div class="panel-ft">
                    <i class="fas fa-info-circle me-1"></i>
                    নিষ্ক্রিয় শাখা ছাত্র যোগ ফর্মে দেখাবে না। শিক্ষার্থী থাকা শাখা মুছা যাবে না।
                </div>
            </div>
        </div>
    </div>

    <script>
    function editRow(b) {
        document.getElementById('id').value = b.id;
        document.getElementById('branch_name').value = b.branch_name || '';
        document.getElementById('branch_code').value = b.branch_code || '';
        document.getElementById('address').value = b.address || '';
        document.getElementById('status').value = b.status || 'active';
        document.getElementById('branch_name').focus();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    function resetForm() {
        document.getElementById('id').value = '';
        document.getElementById('branch_name').value = '';
        document.getElementById('branch_code').value = '';
        document.getElementById('address').value = '';
        document.getElementById('status').value = 'active';
    }
    </script>
</body>
</html>
