<?php
// card_back_page.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'db.php';
require 'helpers.php';

// Get student IDs from URL parameter
$student_ids = $_GET['students'] ?? '';
if (empty($student_ids)) {
    die("No students selected for printing.");
}

// Convert comma-separated IDs to array
$student_ids_array = explode(',', $student_ids);
$placeholders = str_repeat('?,', count($student_ids_array) - 1) . '?';

// Get students data (we only need count for back side)
$sql = "
    SELECT COUNT(*) as total_count
    FROM students s
    WHERE s.student_id IN ($placeholders)
";

$stmt = $mysqli1->prepare($sql);
if ($stmt) {
    $stmt->bind_param(str_repeat('s', count($student_ids_array)), ...$student_ids_array);
    $stmt->execute();
    $result = $stmt->get_result();
    $count_data = $result->fetch_assoc();
    $total_students = $count_data['total_count'];
    $stmt->close();
} else {
    die("Database error: " . $mysqli1->error);
}

if ($total_students === 0) {
    die("No students found with the provided IDs.");
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>طباعة ظهر البطاقات CR80</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Cairo', Arial, sans-serif;
            background: white;
            padding: 0;
            margin: 0;
        }
        
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            .no-print {
                display: none !important;
            }
            .cr80-card {
                page-break-inside: avoid;
                break-inside: avoid;
            }
        }
        
        .print-controls {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            text-align: center;
        }
        
        .btn-print {
            background: linear-gradient(135deg, #27ae60, #2ecc71);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin: 0 10px;
        }
        
        .btn-back {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin: 0 10px;
        }
        
        /* CR80 Cards Layout with 1.5mm gaps - Same as front side */
        .cr80-sheet {
            display: grid;
            grid-template-columns: repeat(3, 54mm);
            grid-template-rows: repeat(3, 85.6mm);
            gap: 1.5mm;
            width: calc(162mm + 3mm);
            height: calc(256.8mm + 3mm);
            margin: 0 auto;
            padding: 0;
            page-break-after: always;
        }
        
        .cr80-card {
            width: 54mm;
            height: 85.6mm;
            border: 0.1mm solid #ccc;
            position: relative;
            overflow: hidden;
            background: white;
        }
        
        /* Back side content - Full background image */
        .back-content {
            width: 100%;
            height: 100%;
            background: url('img/background.png') no-repeat center center;
            background-size: 100% 100%;
            background-position: center;
        }
        
        /* Print Styles */
        @page {
            size: A4 portrait;
            margin: 0;
        }
        
        @media print {
            .cr80-sheet {
                margin: 0 auto;
                padding: 0;
                gap: 1.5mm !important;
            }
            .cr80-card {
                border: 0.1mm solid #ccc;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .back-content {
                background-size: 100% 100% !important;
            }
        }
    </style>
</head>
<body>
    <!-- Print Controls -->
    <div class="print-controls no-print">
        <h2>🃏 طباعة ظهر البطاقات CR80</h2>
        <p class="text-muted">عدد البطاقات: <?php echo $total_students; ?> بطاقة</p>
        <p class="text-muted">الحجم: 54mm × 85.6mm (بطاقة CR80 عمودية)</p>
        <p class="text-muted">🔪 مسافة القص: 1.5mm بين البطاقات</p>
        <p class="text-muted">🎨 التصميم: خلفية موحدة لظهر البطاقة</p>
        <div style="margin-top: 15px;">
            <button class="btn-print" onclick="window.print()">
                <i class="fas fa-print"></i> طباعة الظهر
            </button>
            <button class="btn-back" onclick="window.close()">
                <i class="fas fa-times"></i> إغلاق
            </button>
        </div>
        <div style="margin-top: 10px; font-size: 12px; color: #7f8c8d;">
            💡 سيتم ترتيب البطاقات في صفحات تحتوي كل منها على 9 بطاقات (3×3) مع مسافة قص 1.5mm
        </div>
    </div>

    <!-- Back Side Sheets -->
    <?php
    $students_per_sheet = 9;
    $total_sheets = ceil($total_students / $students_per_sheet);
    
    for ($sheet = 0; $sheet < $total_sheets; $sheet++):
        $start_index = $sheet * $students_per_sheet;
        $end_index = min($start_index + $students_per_sheet, $total_students);
        $cards_on_sheet = $end_index - $start_index;
    ?>
    <div class="cr80-sheet">
        <?php for ($i = 0; $i < $cards_on_sheet; $i++): ?>
        <div class="cr80-card">
            <div class="back-content">
                <!-- Only background image - no student data -->
            </div>
        </div>
        <?php endfor; ?>
        
        <!-- Fill remaining empty slots -->
        <?php for ($i = $cards_on_sheet; $i < $students_per_sheet; $i++): ?>
        <div class="cr80-card">
            <div class="back-content">
                <!-- Empty card with background -->
            </div>
        </div>
        <?php endfor; ?>
    </div>
    <?php endfor; ?>

    <script>
        // Auto-print when page loads (optional)
        window.addEventListener('load', function() {
            // Optional: Uncomment to auto-print
            // window.print();
        });
    </script>
</body>
</html>