<?php

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Tenant;

if (!($auth instanceof Auth) || !$auth->can('branches.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى إدارة الفروع.';
    return;
}

// تشغيل migration للحقول الجديدة
try {
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS branch_type ENUM('branch', 'laboratory', 'collection_center') DEFAULT 'branch' AFTER branch_code");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS manager_name VARCHAR(150) NULL AFTER name");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS manager_phone VARCHAR(30) NULL AFTER manager_name");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS working_hours VARCHAR(100) NULL COMMENT 'ساعات العمل'");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS city VARCHAR(100) NULL AFTER address");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS country VARCHAR(100) NULL DEFAULT 'السعودية' AFTER city");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS postal_code VARCHAR(20) NULL AFTER country");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS website VARCHAR(255) NULL AFTER email");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS notes TEXT NULL");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS capacity INT NULL COMMENT 'القدرة الاستيعابية'");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS services TEXT NULL");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS latitude DECIMAL(10, 8) NULL");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS longitude DECIMAL(11, 8) NULL");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS opening_date DATE NULL");
    $db->exec("ALTER TABLE branches ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP");
} catch (Throwable $e) {
    // تجاهل الأخطاء إذا كانت الأعمدة موجودة بالفعل
}

$action = $_GET['action'] ?? 'index';
$tid = Tenant::id();

$canManageBranches = ($auth instanceof Auth) && $auth->can('branches.manage');

// عرض تفاصيل فرع
if ($action === 'view') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) {
        header('Location: index.php?page=branches');
        exit;
    }
    $stmt = $db->prepare('SELECT * FROM branches WHERE id = ? AND tenant_id = ?');
    $stmt->execute([$id, $tid]);
    $branch = $stmt->fetch();
    if (!$branch) {
        header('Location: index.php?page=branches');
        exit;
    }
    
    // إحصائيات الفرع
    $stats = [];
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE branch_id = ?');
    $stmt->execute([$id]);
    $stats['total_orders'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE branch_id = ? AND DATE(created_at) = CURDATE()');
    $stmt->execute([$id]);
    $stats['today_orders'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM users WHERE branch_id = ?');
    $stmt->execute([$id]);
    $stats['users_count'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT SUM(net_amount) FROM lab_orders WHERE branch_id = ? AND payment_status = ?');
    $stmt->execute([$id, 'paid']);
    $stats['total_revenue'] = (float)($stmt->fetchColumn() ?? 0);
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE branch_id = ? AND status = ?');
    $stmt->execute([$id, 'completed']);
    $stats['completed_orders'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE branch_id = ? AND status IN (?, ?)');
    $stmt->execute([$id, 'new', 'in_progress']);
    $stats['pending_orders'] = (int)$stmt->fetchColumn();
    
    $branchTypeLabels = [
        'branch' => 'فرع',
        'laboratory' => 'مختبر',
        'collection_center' => 'مركز جمع عينات'
    ];
    ?>
    <?php
    $stmt = $db->prepare('SELECT COUNT(*) FROM branches WHERE tenant_id = ?');
    $stmt->execute([$tid]);
    $tenantBranchCount = (int)$stmt->fetchColumn();
    $canDeleteThisBranch = $canManageBranches
        && $stats['total_orders'] === 0
        && $stats['users_count'] === 0
        && $tenantBranchCount > 1;
    ?>
    <div class="page-header">
        <h1><?php echo htmlspecialchars($branch['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <div class="actions-bar" style="flex-wrap:wrap;gap:8px;align-items:center;">
            <?php if ($canManageBranches): ?>
                <a href="index.php?page=branches&action=edit&id=<?php echo (int)$branch['id']; ?>" class="btn-primary">تعديل</a>
            <?php endif; ?>
            <?php if ($canDeleteThisBranch): ?>
                <form method="post" action="index.php?page=branches&action=delete" style="display:inline;" onsubmit="return confirm('حذف هذا الفرع نهائياً؟ لا يمكن التراجع.');">
                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="id" value="<?php echo (int)$branch['id']; ?>">
                    <button type="submit" class="btn-secondary" style="border-color:#dc2626;color:#dc2626;">🗑️ حذف الفرع</button>
                </form>
            <?php elseif ($canManageBranches): ?>
                <span style="font-size:0.9rem;color:var(--text-muted);" title="شروط الحذف">لا يمكن الحذف: <?php
                    $reasons = [];
                    if ($stats['total_orders'] > 0) $reasons[] = 'يوجد طلبات مرتبطة';
                    if ($stats['users_count'] > 0) $reasons[] = 'يوجد مستخدمون مربوطون بالفرع';
                    if ($tenantBranchCount <= 1) $reasons[] = 'يجب بقاء فرع واحد على الأقل';
                    echo htmlspecialchars(implode(' — ', $reasons) ?: 'غير مسموح', ENT_QUOTES, 'UTF-8');
                ?></span>
            <?php endif; ?>
            <a href="index.php?page=branches" class="btn-secondary">رجوع</a>
        </div>
    </div>
    
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--primary);"><?php echo $stats['total_orders']; ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">إجمالي الطلبات</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo $stats['today_orders']; ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">طلبات اليوم</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--warning);"><?php echo $stats['users_count']; ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">عدد المستخدمين</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--info);"><?php echo number_format($stats['total_revenue'], 2); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">إجمالي الإيرادات</div>
        </div>
    </div>
    
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
        <div class="card">
            <h3 style="margin-top:0;">معلومات الفرع</h3>
            <table style="width:100%;">
                <tr><td style="padding:8px 0;font-weight:bold;width:40%;">الكود:</td><td><?php echo htmlspecialchars($branch['branch_code'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">النوع:</td><td><?php echo htmlspecialchars($branchTypeLabels[$branch['branch_type'] ?? 'branch'] ?? 'فرع', ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">الاسم:</td><td><?php echo htmlspecialchars($branch['name'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php if (!empty($branch['manager_name'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">المدير:</td><td><?php echo htmlspecialchars($branch['manager_name'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($branch['address'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">العنوان:</td><td><?php echo htmlspecialchars($branch['address'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($branch['city'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">المدينة:</td><td><?php echo htmlspecialchars($branch['city'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($branch['phone'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">الهاتف:</td><td><?php echo htmlspecialchars($branch['phone'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($branch['email'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">البريد:</td><td><?php echo htmlspecialchars($branch['email'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($branch['working_hours'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">ساعات العمل:</td><td><?php echo htmlspecialchars($branch['working_hours'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <tr><td style="padding:8px 0;font-weight:bold;">الحالة:</td><td><span class="badge badge-<?php echo ($branch['is_active'] ?? 1) ? 'completed' : 'cancelled'; ?>"><?php echo ($branch['is_active'] ?? 1) ? 'نشط' : 'غير نشط'; ?></span></td></tr>
            </table>
        </div>
        
        <div class="card">
            <h3 style="margin-top:0;">إحصائيات الطلبات</h3>
            <table style="width:100%;">
                <tr><td style="padding:8px 0;font-weight:bold;width:50%;">إجمالي الطلبات:</td><td><?php echo $stats['total_orders']; ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">مكتملة:</td><td><span style="color:var(--success);"><?php echo $stats['completed_orders']; ?></span></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">قيد المعالجة:</td><td><span style="color:var(--warning);"><?php echo $stats['pending_orders']; ?></span></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">طلبات اليوم:</td><td><?php echo $stats['today_orders']; ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">إجمالي الإيرادات:</td><td><?php echo number_format($stats['total_revenue'], 2); ?> د.ع</td></tr>
            </table>
        </div>
    </div>
    
    <?php if (!empty($branch['notes'])): ?>
    <div class="card" style="margin-top:16px;">
        <h3 style="margin-top:0;">ملاحظات</h3>
        <p><?php echo nl2br(htmlspecialchars($branch['notes'], ENT_QUOTES, 'UTF-8')); ?></p>
    </div>
    <?php endif; ?>
    
    <?php
    return;
}

// إنشاء فرع جديد
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    if (!$canManageBranches) {
        http_response_code(403);
        echo 'غير مسموح بإضافة فروع.';
        return;
    }
    $code = trim($_POST['branch_code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $branchType = $_POST['branch_type'] ?? 'branch';
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $country = trim($_POST['country'] ?? 'السعودية');
    $postalCode = trim($_POST['postal_code'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $website = trim($_POST['website'] ?? '');
    $managerName = trim($_POST['manager_name'] ?? '');
    $managerPhone = trim($_POST['manager_phone'] ?? '');
    $workingHours = trim($_POST['working_hours'] ?? '');
    $capacity = !empty($_POST['capacity']) ? (int)$_POST['capacity'] : null;
    $services = trim($_POST['services'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $latitude = !empty($_POST['latitude']) ? (float)$_POST['latitude'] : null;
    $longitude = !empty($_POST['longitude']) ? (float)$_POST['longitude'] : null;
    $openingDate = !empty($_POST['opening_date']) ? $_POST['opening_date'] : null;

    if ($code !== '' && $name !== '') {
        try {
            $stmt = $db->prepare('SELECT COALESCE(sp.max_branches, 999) AS mx FROM tenants t LEFT JOIN subscription_plans sp ON sp.id = t.plan_id WHERE t.id = ?');
            $stmt->execute([$tid]);
            $plan = $stmt->fetch();
            $maxBranches = (int)($plan['mx'] ?? 999);
            $stmt = $db->prepare('SELECT COUNT(*) FROM branches WHERE tenant_id = ?');
            $stmt->execute([$tid]);
            $currentBranches = (int)$stmt->fetchColumn();
            if ($currentBranches >= $maxBranches) {
                $createError = 'تم الوصول لحد الفروع المسموح به (' . $maxBranches . '). قم بترقية الاشتراك.';
            } else {
                $sql = 'INSERT INTO branches (branch_code, branch_type, name, manager_name, manager_phone, address, city, country, postal_code, phone, email, website, working_hours, capacity, services, notes, latitude, longitude, opening_date, is_active, tenant_id) VALUES (:code, :type, :name, :mgr_name, :mgr_phone, :addr, :city, :country, :postal, :phone, :email, :website, :hours, :capacity, :services, :notes, :lat, :lng, :opening, 1, :tid)';
                $stmt = $db->prepare($sql);
                $stmt->execute([
                    'code' => $code,
                    'type' => $branchType,
                    'name' => $name,
                    'mgr_name' => $managerName ?: null,
                    'mgr_phone' => $managerPhone ?: null,
                    'addr' => $address ?: null,
                    'city' => $city ?: null,
                    'country' => $country ?: null,
                    'postal' => $postalCode ?: null,
                    'phone' => $phone ?: null,
                    'email' => $email ?: null,
                    'website' => $website ?: null,
                    'hours' => $workingHours ?: null,
                    'capacity' => $capacity,
                    'services' => $services ?: null,
                    'notes' => $notes ?: null,
                    'lat' => $latitude,
                    'lng' => $longitude,
                    'opening' => $openingDate ?: null,
                    'tid' => $tid
                ]);
                if (isset($auditLog)) {
                    $auditLog->log('branch_created', 'branch', (int)$db->lastInsertId(), null, json_encode(['branch_code' => $code, 'name' => $name], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
                header('Location: index.php?page=branches&created=1');
                exit;
            }
        } catch (PDOException $e) {
            $createError = 'الكود مستخدم مسبقاً أو حدث خطأ: ' . $e->getMessage();
        }
    }
}

// تعديل فرع
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    if (!$canManageBranches) {
        http_response_code(403);
        echo 'غير مسموح بتعديل الفروع.';
        return;
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $code = trim($_POST['branch_code'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $branchType = $_POST['branch_type'] ?? 'branch';
        $address = trim($_POST['address'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $country = trim($_POST['country'] ?? 'السعودية');
        $postalCode = trim($_POST['postal_code'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $website = trim($_POST['website'] ?? '');
        $managerName = trim($_POST['manager_name'] ?? '');
        $managerPhone = trim($_POST['manager_phone'] ?? '');
        $workingHours = trim($_POST['working_hours'] ?? '');
        $capacity = !empty($_POST['capacity']) ? (int)$_POST['capacity'] : null;
        $services = trim($_POST['services'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        $latitude = !empty($_POST['latitude']) ? (float)$_POST['latitude'] : null;
        $longitude = !empty($_POST['longitude']) ? (float)$_POST['longitude'] : null;
        $openingDate = !empty($_POST['opening_date']) ? $_POST['opening_date'] : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($code !== '' && $name !== '') {
            $sql = 'UPDATE branches SET branch_code=:code, branch_type=:type, name=:name, manager_name=:mgr_name, manager_phone=:mgr_phone, address=:addr, city=:city, country=:country, postal_code=:postal, phone=:phone, email=:email, website=:website, working_hours=:hours, capacity=:capacity, services=:services, notes=:notes, latitude=:lat, longitude=:lng, opening_date=:opening, is_active=:active WHERE id=:id';
            $stmt = $db->prepare($sql);
            $stmt->execute([
                'code' => $code,
                'type' => $branchType,
                'name' => $name,
                'mgr_name' => $managerName ?: null,
                'mgr_phone' => $managerPhone ?: null,
                'addr' => $address ?: null,
                'city' => $city ?: null,
                'country' => $country ?: null,
                'postal' => $postalCode ?: null,
                'phone' => $phone ?: null,
                'email' => $email ?: null,
                'website' => $website ?: null,
                'hours' => $workingHours ?: null,
                'capacity' => $capacity,
                'services' => $services ?: null,
                'notes' => $notes ?: null,
                'lat' => $latitude,
                'lng' => $longitude,
                'opening' => $openingDate ?: null,
                'active' => $isActive,
                'id' => $id
            ]);
            if (isset($auditLog)) {
                $auditLog->log('branch_updated', 'branch', $id, null, json_encode(['branch_code' => $code, 'name' => $name], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            }
            header('Location: index.php?page=branches&updated=1');
            exit;
        }
    }
}

// حذف فرع (بعد التحقق من المستأجر، الطلبات، المستخدمين، وبقاء فرع واحد على الأقل)
if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    if (!$canManageBranches) {
        http_response_code(403);
        echo 'غير مسموح بحذف الفروع.';
        return;
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $db->prepare('SELECT branch_code, name FROM branches WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$id, $tid]);
        $br = $stmt->fetch();
        if (!$br) {
            header('Location: index.php?page=branches&error=not_found');
            exit;
        }
        $stmt = $db->prepare('SELECT COUNT(*) FROM branches WHERE tenant_id = ?');
        $stmt->execute([$tid]);
        if ((int)$stmt->fetchColumn() <= 1) {
            header('Location: index.php?page=branches&error=last_branch');
            exit;
        }
        $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE branch_id = ?');
        $stmt->execute([$id]);
        if ((int)$stmt->fetchColumn() > 0) {
            header('Location: index.php?page=branches&error=cannot_delete');
            exit;
        }
        $stmt = $db->prepare('SELECT COUNT(*) FROM users WHERE branch_id = ?');
        $stmt->execute([$id]);
        if ((int)$stmt->fetchColumn() > 0) {
            header('Location: index.php?page=branches&error=cannot_delete_users');
            exit;
        }
        try {
            $db->prepare('DELETE FROM branches WHERE id = ? AND tenant_id = ?')->execute([$id, $tid]);
        } catch (Throwable $e) {
            header('Location: index.php?page=branches&error=cannot_delete_fk');
            exit;
        }
        if (isset($auditLog)) {
            $auditLog->log('branch_deleted', 'branch', $id, json_encode($br, JSON_UNESCAPED_UNICODE), null, $_SESSION['user_id'] ?? null);
        }
        header('Location: index.php?page=branches&deleted=1');
        exit;
    }
}

// عرض نموذج الإضافة
if ($action === 'create') {
    if (!$canManageBranches) {
        http_response_code(403);
        echo 'غير مسموح بإضافة فروع.';
        return;
    }
    ?>
    <div class="page-header">
        <h1>إضافة فرع / مختبر جديد</h1>
    </div>
    <div class="card">
    <form method="post" class="form-grid">
        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
        <div>
            <label>كود الفرع <span style="color:red;">*</span></label>
            <input type="text" name="branch_code" required placeholder="مثال: BR2">
        </div>
        <div>
            <label>نوع الفرع <span style="color:red;">*</span></label>
            <select name="branch_type" required>
                <option value="branch">فرع</option>
                <option value="laboratory">مختبر</option>
                <option value="collection_center">مركز جمع عينات</option>
            </select>
        </div>
        <div class="full-width">
            <label>اسم الفرع / المختبر <span style="color:red;">*</span></label>
            <input type="text" name="name" required placeholder="اسم المختبر أو الفرع">
        </div>
        <div>
            <label>اسم المدير</label>
            <input type="text" name="manager_name" placeholder="اسم مدير الفرع">
        </div>
        <div>
            <label>هاتف المدير</label>
            <input type="text" name="manager_phone" placeholder="05xxxxxxxx">
        </div>
        <div class="full-width">
            <label>العنوان</label>
            <input type="text" name="address" placeholder="العنوان التفصيلي">
        </div>
        <div>
            <label>المدينة</label>
            <input type="text" name="city" placeholder="المدينة">
        </div>
        <div>
            <label>الدولة</label>
            <input type="text" name="country" value="السعودية" placeholder="الدولة">
        </div>
        <div>
            <label>الرمز البريدي</label>
            <input type="text" name="postal_code" placeholder="12345">
        </div>
        <div>
            <label>الهاتف</label>
            <input type="text" name="phone" placeholder="05xxxxxxxx">
        </div>
        <div>
            <label>البريد الإلكتروني</label>
            <input type="email" name="email" placeholder="example@domain.com">
        </div>
        <div>
            <label>الموقع الإلكتروني</label>
            <input type="url" name="website" placeholder="https://example.com">
        </div>
        <div>
            <label>ساعات العمل</label>
            <input type="text" name="working_hours" placeholder="8:00 - 17:00">
        </div>
        <div>
            <label>القدرة الاستيعابية اليومية</label>
            <input type="number" name="capacity" min="0" placeholder="عدد الطلبات">
        </div>
        <div>
            <label>خط العرض (Latitude)</label>
            <input type="number" step="any" name="latitude" placeholder="24.7136">
        </div>
        <div>
            <label>خط الطول (Longitude)</label>
            <input type="number" step="any" name="longitude" placeholder="46.6753">
        </div>
        <div>
            <label>تاريخ الافتتاح</label>
            <input type="date" name="opening_date">
        </div>
        <div class="full-width">
            <label>الخدمات المقدمة</label>
            <textarea name="services" rows="3" placeholder="قائمة الخدمات المقدمة"></textarea>
        </div>
        <div class="full-width">
            <label>ملاحظات</label>
            <textarea name="notes" rows="3" placeholder="ملاحظات إضافية"></textarea>
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ</button>
            <a href="index.php?page=branches" class="btn-secondary">رجوع</a>
        </div>
    </form>
    </div>
    <?php
    if (!empty($createError)): ?>
    <div class="alert alert-danger" style="margin-top:16px;"><?php echo htmlspecialchars($createError, ENT_QUOTES, 'UTF-8'); ?></div>
    <?php endif;
    return;
}

// عرض نموذج التعديل
if ($action === 'edit') {
    if (!$canManageBranches) {
        http_response_code(403);
        echo 'غير مسموح بتعديل الفروع.';
        return;
    }
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) {
        header('Location: index.php?page=branches');
        exit;
    }
    $stmt = $db->prepare('SELECT * FROM branches WHERE id = ? AND tenant_id = ?');
    $stmt->execute([$id, $tid]);
    $branch = $stmt->fetch();
    if (!$branch) {
        header('Location: index.php?page=branches');
        exit;
    }
    ?>
    <div class="page-header">
        <h1>تعديل الفرع: <?php echo htmlspecialchars($branch['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
    </div>
    <div class="card">
    <form method="post" class="form-grid">
        <input type="hidden" name="id" value="<?php echo (int)$branch['id']; ?>">
        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
        <div>
            <label>كود الفرع <span style="color:red;">*</span></label>
            <input type="text" name="branch_code" required value="<?php echo htmlspecialchars($branch['branch_code'], ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>نوع الفرع <span style="color:red;">*</span></label>
            <select name="branch_type" required>
                <option value="branch" <?php echo ($branch['branch_type'] ?? 'branch') === 'branch' ? 'selected' : ''; ?>>فرع</option>
                <option value="laboratory" <?php echo ($branch['branch_type'] ?? '') === 'laboratory' ? 'selected' : ''; ?>>مختبر</option>
                <option value="collection_center" <?php echo ($branch['branch_type'] ?? '') === 'collection_center' ? 'selected' : ''; ?>>مركز جمع عينات</option>
            </select>
        </div>
        <div class="full-width">
            <label>اسم الفرع / المختبر <span style="color:red;">*</span></label>
            <input type="text" name="name" required value="<?php echo htmlspecialchars($branch['name'], ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>اسم المدير</label>
            <input type="text" name="manager_name" value="<?php echo htmlspecialchars($branch['manager_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>هاتف المدير</label>
            <input type="text" name="manager_phone" value="<?php echo htmlspecialchars($branch['manager_phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div class="full-width">
            <label>العنوان</label>
            <input type="text" name="address" value="<?php echo htmlspecialchars($branch['address'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>المدينة</label>
            <input type="text" name="city" value="<?php echo htmlspecialchars($branch['city'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الدولة</label>
            <input type="text" name="country" value="<?php echo htmlspecialchars($branch['country'] ?? 'السعودية', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الرمز البريدي</label>
            <input type="text" name="postal_code" value="<?php echo htmlspecialchars($branch['postal_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الهاتف</label>
            <input type="text" name="phone" value="<?php echo htmlspecialchars($branch['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>البريد الإلكتروني</label>
            <input type="email" name="email" value="<?php echo htmlspecialchars($branch['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>الموقع الإلكتروني</label>
            <input type="url" name="website" value="<?php echo htmlspecialchars($branch['website'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div>
            <label>ساعات العمل</label>
            <input type="text" name="working_hours" value="<?php echo htmlspecialchars($branch['working_hours'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="8:00 - 17:00">
        </div>
        <div>
            <label>القدرة الاستيعابية اليومية</label>
            <input type="number" name="capacity" min="0" value="<?php echo $branch['capacity'] ?? ''; ?>" placeholder="عدد الطلبات">
        </div>
        <div>
            <label>خط العرض (Latitude)</label>
            <input type="number" step="any" name="latitude" value="<?php echo $branch['latitude'] ?? ''; ?>" placeholder="24.7136">
        </div>
        <div>
            <label>خط الطول (Longitude)</label>
            <input type="number" step="any" name="longitude" value="<?php echo $branch['longitude'] ?? ''; ?>" placeholder="46.6753">
        </div>
        <div>
            <label>تاريخ الافتتاح</label>
            <input type="date" name="opening_date" value="<?php echo $branch['opening_date'] ?? ''; ?>">
        </div>
        <div class="full-width">
            <label>الخدمات المقدمة</label>
            <textarea name="services" rows="3" placeholder="قائمة الخدمات المقدمة"><?php echo htmlspecialchars($branch['services'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
        </div>
        <div class="full-width">
            <label>ملاحظات</label>
            <textarea name="notes" rows="3" placeholder="ملاحظات إضافية"><?php echo htmlspecialchars($branch['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
        </div>
        <div>
            <label style="display:flex;align-items:center;gap:8px;">
                <input type="checkbox" name="is_active" <?php echo ($branch['is_active'] ?? 1) ? 'checked' : ''; ?>>
                الفرع نشط
            </label>
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ التعديلات</button>
            <a href="index.php?page=branches&action=view&id=<?php echo (int)$branch['id']; ?>" class="btn-secondary">عرض التفاصيل</a>
            <a href="index.php?page=branches" class="btn-secondary">رجوع</a>
        </div>
    </form>
    </div>
    <?php
    return;
}

// قائمة الفروع
$branches = [];
$branchSearch = trim($_GET['q'] ?? '');
$branchFilter = $_GET['filter'] ?? '';
$branchExport = isset($_GET['export']) && $_GET['export'] === 'csv';
$branchPage = max(1, (int)($_GET['p'] ?? 1));
$branchPerPage = 25;
$branchOffset = ($branchPage - 1) * $branchPerPage;
try {
    $baseSql = 'SELECT b.*, 
        (SELECT COUNT(*) FROM lab_orders o WHERE o.branch_id = b.id) AS orders_count,
        (SELECT COUNT(*) FROM users u WHERE u.branch_id = b.id) AS users_count
        FROM branches b';
    $where = ' WHERE b.tenant_id = ?';
    $params = [$tid];
    if ($branchSearch !== '') {
        $where .= ' AND (b.name LIKE ? OR b.branch_code LIKE ? OR b.address LIKE ? OR b.phone LIKE ? OR b.city LIKE ? OR b.manager_name LIKE ?)';
        $params = array_merge($params, ['%' . $branchSearch . '%', '%' . $branchSearch . '%', '%' . $branchSearch . '%', '%' . $branchSearch . '%', '%' . $branchSearch . '%', '%' . $branchSearch . '%']);
    }
    if ($branchFilter === 'active') {
        $where .= ' AND b.is_active = 1';
    } elseif ($branchFilter === 'inactive') {
        $where .= ' AND b.is_active = 0';
    } elseif ($branchFilter && in_array($branchFilter, ['branch', 'laboratory', 'collection_center'])) {
        $where .= ' AND b.branch_type = ?';
        $params[] = $branchFilter;
    }
    $order = ' ORDER BY b.created_at DESC';
    if ($branchExport) {
        $stmt = $params ? $db->prepare($baseSql . $where . $order) : $db->query($baseSql . $order);
        if ($params) $stmt->execute($params);
        $branches = $stmt->fetchAll();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="branches_' . date('Y-m-d') . '.csv"');
        echo "\xEF\xBB\xBF";
        echo "الكود,النوع,الاسم,المدير,المدينة,العنوان,الهاتف,البريد,عدد الطلبات,عدد المستخدمين,الحالة\n";
        foreach ($branches as $b) {
            $typeLabels = ['branch' => 'فرع', 'laboratory' => 'مختبر', 'collection_center' => 'مركز جمع'];
            $line = [
                $b['branch_code'],
                $typeLabels[$b['branch_type'] ?? 'branch'] ?? 'فرع',
                $b['name'],
                $b['manager_name'] ?? '',
                $b['city'] ?? '',
                $b['address'] ?? '',
                $b['phone'] ?? '',
                $b['email'] ?? '',
                $b['orders_count'] ?? 0,
                $b['users_count'] ?? 0,
                ($b['is_active'] ?? 1) ? 'نشط' : 'غير نشط'
            ];
            $escaped = [];
            foreach ($line as $v) {
                $v = (string)$v;
                if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
                $escaped[] = $v;
            }
            echo implode(',', $escaped) . "\n";
        }
        exit;
    }
    $limit = ' LIMIT ' . (int)$branchPerPage . ' OFFSET ' . (int)$branchOffset;
    $stmt = $params ? $db->prepare($baseSql . $where . $order . $limit) : $db->query($baseSql . $order . $limit);
    if ($params) $stmt->execute($params);
    $branches = $stmt->fetchAll();
    $cntSql = 'SELECT COUNT(*) FROM branches b' . $where;
    $stmt = $params ? $db->prepare($cntSql) : $db->query($cntSql);
    if ($params) $stmt->execute($params);
    $branchTotal = (int)($stmt->fetchColumn() ?? 0);
    $branchTotalPages = $branchTotal > 0 ? (int)ceil($branchTotal / $branchPerPage) : 1;
} catch (Throwable $e) {
    $branchTotalPages = 1;
    $branchPage = 1;
}

$tenantBranchCount = 0;
try {
    $stmt = $db->prepare('SELECT COUNT(*) FROM branches WHERE tenant_id = ?');
    $stmt->execute([$tid]);
    $tenantBranchCount = (int)$stmt->fetchColumn();
} catch (Throwable $e) {
}

$msg = '';
if (isset($_GET['created'])) $msg = 'تم إضافة الفرع بنجاح.';
if (isset($_GET['updated'])) $msg = 'تم تحديث الفرع بنجاح.';
if (isset($_GET['deleted'])) $msg = 'تم حذف الفرع بنجاح.';
if (isset($_GET['error'])) {
    switch ($_GET['error']) {
        case 'cannot_delete':
            $msg = 'لا يمكن حذف الفرع لأنه يحتوي على طلبات.';
            break;
        case 'cannot_delete_users':
            $msg = 'لا يمكن حذف الفرع: انقل المستخدمين المربوطين به إلى فرع آخر أولاً.';
            break;
        case 'last_branch':
            $msg = 'لا يمكن حذف آخر فرع للمختبر — يجب بقاء فرع واحد على الأقل.';
            break;
        case 'not_found':
            $msg = 'الفرع غير موجود أو لا يخص حسابك.';
            break;
        case 'cannot_delete_fk':
            $msg = 'لا يمكن الحذف: يوجد بيانات مرتبطة أخرى بهذا الفرع.';
            break;
        default:
            $msg = 'تعذّر تنفيذ العملية.';
    }
}
$branchListAlertClass = isset($_GET['error']) ? 'alert-danger' : 'alert-info';

$branchTypeLabels = [
    'branch' => 'فرع',
    'laboratory' => 'مختبر',
    'collection_center' => 'مركز جمع عينات'
];
?>
<div class="page-header page-header--stack">
    <div class="page-header-top">
        <h1>إدارة الفروع والمختبرات</h1>
        <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
            <form method="get" style="display:inline-flex;gap:6px;flex-wrap:wrap;">
                <input type="hidden" name="page" value="branches">
                <input type="search" name="q" placeholder="بحث..." value="<?php echo htmlspecialchars($branchSearch ?? '', ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;">
                <select name="filter" style="min-width:120px;">
                    <option value="">جميع الفروع</option>
                    <option value="active" <?php echo $branchFilter === 'active' ? 'selected' : ''; ?>>نشطة فقط</option>
                    <option value="inactive" <?php echo $branchFilter === 'inactive' ? 'selected' : ''; ?>>غير نشطة</option>
                    <option value="laboratory" <?php echo $branchFilter === 'laboratory' ? 'selected' : ''; ?>>مختبرات</option>
                    <option value="collection_center" <?php echo $branchFilter === 'collection_center' ? 'selected' : ''; ?>>مراكز جمع</option>
                </select>
                <button type="submit">بحث</button>
                <?php if (!empty($branchSearch) || !empty($branchFilter)): ?><a href="index.php?page=branches" class="btn-secondary">إلغاء</a><?php endif; ?>
            </form>
            <a href="index.php?page=branches&export=csv<?php echo $branchSearch ? '&q=' . urlencode($branchSearch) : ''; echo $branchFilter ? '&filter=' . urlencode($branchFilter) : ''; ?>" class="btn-secondary">تصدير CSV</a>
            <?php if ($canManageBranches): ?><a href="index.php?page=branches&action=create" class="btn-primary">➕ فرع جديد</a><?php endif; ?>
        </div>
    </div>
    <p class="page-header-desc">تعريف الفروع والمختبرات ومراكز الجمع مع ربط المستخدمين والطلبات. استخدم التصفية للتمييز بين نوع المنشأة وحالة النشاط.</p>
    <nav class="lab-quick-nav" aria-label="اختصارات ذات صلة">
        <?php if ($auth->can('branches.manage')): ?><a href="index.php?page=branch_central">لوحة أداء الفروع</a><?php endif; ?>
        <?php if ($auth->can('orders.view')): ?><a href="index.php?page=orders">طلبات الفحوصات</a><?php endif; ?>
        <?php if ($auth->can('reports.view')): ?><a href="index.php?page=reports">التقارير</a><?php endif; ?>
    </nav>
</div>
<?php if ($msg): ?>
<div class="alert <?php echo htmlspecialchars($branchListAlertClass, ENT_QUOTES, 'UTF-8'); ?>" style="margin-bottom:16px;"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<div class="table-wrapper">
<table class="table">
    <thead>
        <tr>
            <th>الكود</th>
            <th>النوع</th>
            <th>الاسم</th>
            <th>المدير</th>
            <th>المدينة</th>
            <th>الهاتف</th>
            <th>الطلبات</th>
            <th>المستخدمين</th>
            <th>الحالة</th>
            <th>إجراءات</th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($branches)): ?>
        <tr><td colspan="10" style="text-align:center;padding:24px;color:var(--text-muted);">لا توجد فروع</td></tr>
    <?php else: ?>
    <?php foreach ($branches as $b): ?>
        <tr>
            <td><strong><?php echo htmlspecialchars($b['branch_code'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
            <td><span class="badge badge-info"><?php echo htmlspecialchars($branchTypeLabels[$b['branch_type'] ?? 'branch'] ?? 'فرع', ENT_QUOTES, 'UTF-8'); ?></span></td>
            <td><?php echo htmlspecialchars($b['name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($b['manager_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($b['city'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($b['phone'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo (int)($b['orders_count'] ?? 0); ?></td>
            <td><?php echo (int)($b['users_count'] ?? 0); ?></td>
            <td><span class="badge badge-<?php echo ($b['is_active'] ?? 1) ? 'completed' : 'cancelled'; ?>"><?php echo ($b['is_active'] ?? 1) ? 'نشط' : 'غير نشط'; ?></span></td>
            <td>
                <a href="index.php?page=branches&action=view&id=<?php echo (int)$b['id']; ?>" class="btn-link" title="عرض التفاصيل">👁️</a>
                <?php if ($canManageBranches): ?>
                    <a href="index.php?page=branches&action=edit&id=<?php echo (int)$b['id']; ?>" class="btn-link" title="تعديل">✏️</a>
                <?php endif; ?>
                <?php if ($canManageBranches && (int)($b['orders_count'] ?? 0) === 0 && (int)($b['users_count'] ?? 0) === 0 && $tenantBranchCount > 1): ?>
                    <form method="post" action="index.php?page=branches&action=delete" style="display:inline;" onsubmit="return confirm('حذف هذا الفرع نهائياً؟');">
                        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="id" value="<?php echo (int)$b['id']; ?>">
                        <button type="submit" class="btn-link" style="color:#dc2626;" title="حذف">🗑️</button>
                    </form>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
</table>
</div>
<?php if (isset($branchTotalPages) && $branchTotalPages > 1): ?>
<div class="pagination" style="margin-top:16px;">
    <?php $baseUrl = 'index.php?page=branches' . ($branchSearch ? '&q=' . urlencode($branchSearch) : '') . ($branchFilter ? '&filter=' . urlencode($branchFilter) : ''); for ($i = 1; $i <= min($branchTotalPages, 10); $i++): ?><a href="<?php echo $baseUrl . '&p=' . $i; ?>"<?php echo $i === $branchPage ? ' style="font-weight:bold;"' : ''; ?>><?php echo $i; ?></a><?php endfor; ?>
</div>
<?php endif; ?>
