<?php 
include 'config.php'; 
include 'header.php'; 

// 1. إضافة فرع جديد
if(isset($_POST['add_branch'])){
    $b_name = $_POST['branch_name'];
    $b_location = $_POST['location'];
    
    $stmt = $pdo->prepare("INSERT INTO branches (branch_name, location) VALUES (?, ?)");
    $stmt->execute([$b_name, $b_location]);
    echo "<script>alert('تم إضافة الفرع بنجاح');</script>";
}

// [تعديل الـ SQL المطور]: جلب الفروع والورديات مع فرز وحساب إجمالي مبيعات كل عملة بشكل مستقل
$branches = $pdo->query("SELECT * FROM branches")->fetchAll();

$shifts_sql = "SELECT s.*, u.full_name, b.branch_name,
               IFNULL((SELECT SUM(paid_amount) FROM orders WHERE shift_id = s.id AND currency = 'EGP'), 0) as sales_egp,
               IFNULL((SELECT SUM(paid_amount) FROM orders WHERE shift_id = s.id AND currency = 'USD'), 0) as sales_usd,
               IFNULL((SELECT SUM(paid_amount) FROM orders WHERE shift_id = s.id AND currency = 'JPY'), 0) as sales_jpy
               FROM shifts s 
               JOIN users u ON s.user_id = u.id 
               JOIN branches b ON s.branch_id = b.id 
               ORDER BY s.start_time DESC LIMIT 20";
$shifts = $pdo->query($shifts_sql)->fetchAll();
?>

<!-- استايل مخصص لترتيب العملات بشكل أنيق داخل الخلايا بدون تضخيم عرض الجدول -->
<style>
    .currency-row { display: flex; justify-content: space-between; align-items: center; font-size: 0.88rem; padding: 2px 0; border-bottom: 1px dashed #eee; }
    .currency-row:last-child { border-bottom: none; }
    .currency-label { font-size: 0.75rem; font-weight: bold; padding: 1px 4px; border-radius: 3px; }
    .bg-egp { background-color: #e9ecef; color: #495057; }
    .bg-usd { background-color: #e8f5e9; color: #2e7d32; }
    .bg-jpy { background-color: #fff3e0; color: #ef6c00; }
</style>

<div class="action-bar d-flex justify-content-between">
    <h5 class="m-0"><i class="fa fa-sitemap me-2"></i> هيكل الإدارة والورديات</h5>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addBranchModal">
        <i class="fa fa-plus"></i> إضافة فرع جديد
    </button>
</div>

<div class="container-fluid mt-4">
    <div class="row">
        <!-- الفروع الحالية -->
        <div class="col-md-3">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white fw-bold">الفروع الحالية</div>
                <div class="list-group list-group-flush">
                    <?php foreach($branches as $br): ?>
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <i class="fa fa-store text-primary me-2"></i>
                                <strong><?= htmlspecialchars($br['branch_name']) ?></strong>
                                <div class="small text-muted"><?= htmlspecialchars($br['location']) ?></div>
                            </div>
                            <?php if($br['is_main']): ?>
                                <span class="badge bg-info">الرئيسي</span>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- سجل ومراقبة الخزينة والورديات والـ Cash Flow المتعدد العملات -->
        <div class="col-md-9">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white fw-bold">سجل ومراقبة الخزينة والورديات والـ Cash Flow (متعدد العملات)</div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover align-middle mb-0 text-center">
                        <thead class="table-light">
                            <tr>
                                <th class="text-start" style="min-width: 160px;">الموظف/الفرع</th>
                                <th>بداية الوردية</th>
                                <th>الحالة</th>
                                <th style="min-width: 130px;">الافتتاحي بالدرج</th>
                                <th style="min-width: 130px;">المبيعات المحصلة</th>
                                <th style="min-width: 140px;">المفترض بالخزنة</th>
                                <th style="min-width: 130px;">الفعلي عند الإغلاق</th>
                                <th style="min-width: 150px;">التسوية والـجرد (عجز/زيادة)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($shifts as $sh): 
                                // احتساب القيمة البرمجية المفترضة لكل عملة على حدة
                                $expected_egp = $sh['cash_start'] + $sh['sales_egp'];
                                $expected_usd = $sh['cash_start_usd'] + $sh['sales_usd'];
                                $expected_jpy = $sh['cash_start_jpy'] + $sh['sales_jpy'];
                            ?>
                            <tr>
                                <td class="text-start">
                                    <i class="fa fa-user text-muted me-1"></i> 
                                    <strong><?= htmlspecialchars($sh['full_name']) ?></strong>
                                    <div class="small text-muted" style="margin-right: 18px;"><?= htmlspecialchars($sh['branch_name']) ?></div>
                                </td>
                                <td class="small text-muted"><?= $sh['start_time'] ?></td>
                                <td>
                                    <?php if($sh['status'] == 'open'): ?>
                                        <span class="badge bg-success-subtle text-success p-2"><i class="fa fa-circle me-1"></i> مفتوحة</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary-subtle text-muted p-2">مغلقة</span>
                                    <?php endif; ?>
                                </td>
                                
                                <!-- 1. الأرصدة الافتتاحية -->
                                <td>
                                    <div class="currency-row">
                                        <span class="currency-label bg-egp">EGP</span>
                                        <span class="fw-bold text-secondary"><?= number_format($sh['cash_start'], 2) ?></span>
                                    </div>
                                    <div class="currency-row">
                                        <span class="currency-label bg-usd">USD</span>
                                        <span class="fw-bold text-secondary"><?= number_format($sh['cash_start_usd'], 2) ?></span>
                                    </div>
                                    <div class="currency-row">
                                        <span class="currency-label bg-jpy">JPY</span>
                                        <span class="fw-bold text-secondary"><?= number_format($sh['cash_start_jpy'], 0) ?></span>
                                    </div>
                                </td>
                                
                                <!-- 2. المبيعات المحصلة بالعملات -->
                                <td>
                                    <div class="currency-row">
                                        <span class="currency-label bg-egp">EGP</span>
                                        <span class="fw-bold text-info"><?= number_format($sh['sales_egp'], 2) ?></span>
                                    </div>
                                    <div class="currency-row">
                                        <span class="currency-label bg-usd">USD</span>
                                        <span class="fw-bold text-info"><?= number_format($sh['sales_usd'], 2) ?></span>
                                    </div>
                                    <div class="currency-row">
                                        <span class="currency-label bg-jpy">JPY</span>
                                        <span class="fw-bold text-info"><?= number_format($sh['sales_jpy'], 0) ?></span>
                                    </div>
                                </td>
                                
                                <!-- 3. المفترض وجوده في الخزنة -->
                                <td>
                                    <div class="currency-row">
                                        <span class="currency-label bg-egp">EGP</span>
                                        <span class="fw-bold text-dark"><?= number_format($expected_egp, 2) ?></span>
                                    </div>
                                    <div class="currency-row">
                                        <span class="currency-label bg-usd">USD</span>
                                        <span class="fw-bold text-dark"><?= number_format($expected_usd, 2) ?></span>
                                    </div>
                                    <div class="currency-row">
                                        <span class="currency-label bg-jpy">JPY</span>
                                        <span class="fw-bold text-dark"><?= number_format($expected_jpy, 0) ?></span>
                                    </div>
                                </td>
                                
                                <!-- 4. الفعلي المستلم من الكاشير -->
                                <td>
                                    <?php if($sh['status'] == 'open'): ?>
                                        <span class="text-muted font-monospace small">جاري العمل...</span>
                                    <?php else: ?>
                                        <div class="currency-row">
                                            <span class="currency-label bg-egp">EGP</span>
                                            <span class="fw-bold text-success"><?= number_format($sh['cash_end'], 2) ?></span>
                                        </div>
                                        <div class="currency-row">
                                            <span class="currency-label bg-usd">USD</span>
                                            <span class="fw-bold text-success"><?= number_format($sh['cash_end_usd'], 2) ?></span>
                                        </div>
                                        <div class="currency-row">
                                            <span class="currency-label bg-jpy">JPY</span>
                                            <span class="fw-bold text-success"><?= number_format($sh['cash_end_jpy'], 0) ?></span>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                
                                <!-- 5. الفرز وحساب الفروقات مستقلة -->
                                <td>
                                    <?php if($sh['status'] == 'open'): ?>
                                        <span class="text-muted">-</span>
                                    <?php else: ?>
                                        <!-- جرد الجنيه -->
                                        <div class="currency-row">
                                            <span class="currency-label bg-egp">EGP</span>
                                            <?php 
                                            $diff_egp = $sh['cash_end'] - $expected_egp;
                                            if(abs($diff_egp) < 0.01) echo '<span class="badge bg-success py-1">مطابق</span>';
                                            elseif($diff_egp > 0) echo '<span class="text-success fw-bold">+' . number_format($diff_egp, 2) . '</span>';
                                            else echo '<span class="text-danger fw-bold">' . number_format($diff_egp, 2) . '</span>';
                                            ?>
                                        </div>
                                        
                                        <!-- جرد الدولار -->
                                        <div class="currency-row">
                                            <span class="currency-label bg-usd">USD</span>
                                            <?php 
                                            $diff_usd = $sh['cash_end_usd'] - $expected_usd;
                                            if(abs($diff_usd) < 0.01) echo '<span class="badge bg-success py-1">مطابق</span>';
                                            elseif($diff_usd > 0) echo '<span class="text-success fw-bold">+' . number_format($diff_usd, 2) . '</span>';
                                            else echo '<span class="text-danger fw-bold">' . number_format($diff_usd, 2) . '</span>';
                                            ?>
                                        </div>

                                        <!-- جرد الين -->
                                        <div class="currency-row">
                                            <span class="currency-label bg-jpy">JPY</span>
                                            <?php 
                                            $diff_jpy = $sh['cash_end_jpy'] - $expected_jpy;
                                            if(abs($diff_jpy) < 0.01) echo '<span class="badge bg-success py-1">مطابق</span>';
                                            elseif($diff_jpy > 0) echo '<span class="text-success fw-bold">+' . number_format($diff_jpy, 0) . '</span>';
                                            else echo '<span class="text-danger fw-bold">' . number_format($diff_jpy, 0) . '</span>';
                                            ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- المودال الخاص بإضافة فرع جديد -->
<div class="modal fade" id="addBranchModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content border-0">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">إضافة فرع جديد</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">اسم الفرع</label>
                    <input type="text" name="branch_name" class="form-control" placeholder="مثلاً: فرع مدينة نصر" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">العنوان / الموقع</label>
                    <input type="text" name="location" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" name="add_branch" class="btn btn-primary w-100">حفظ الفرع</button>
            </div>
        </form>
    </div>
</div>

<?php include 'footer.php'; ?>