<?php
require_once __DIR__ . '/registration_helpers.php';
$conn = sr_connect();
sr_install($conn);
$error = '';
$success = '';
if(isset($_GET['success']) && $_GET['success']=='1'){
    $success = 'تم إدخال معلومات الطالب بنجاح. يجب مراجعة الإدارة لإكمال التسجيل.';
}

if($_SERVER['REQUEST_METHOD']=='POST'){
    $registration_no = sr_generate_registration_no($conn);
    $registration_token = sr_generate_token();
    $student_full_name = clean_input($_POST['student_full_name']);
    $gender = clean_input($_POST['gender']);
    $birth_date = clean_input($_POST['birth_date']);
    $stage = clean_input($_POST['stage']);
    $previous_school = clean_input($_POST['previous_school']);
    $guardian_name = clean_input($_POST['guardian_name']);
    $guardian_relation = clean_input($_POST['guardian_relation']);
    $guardian_phone = clean_input($_POST['guardian_phone']);
    $guardian_whatsapp = clean_input($_POST['guardian_whatsapp']);
    $guardian_job = clean_input($_POST['guardian_job']);
    $address = clean_input($_POST['address']);
    $map_lat = clean_input($_POST['map_lat']);
    $map_lng = clean_input($_POST['map_lng']);
    $map_link = clean_input($_POST['map_link']);
    $mother_name = clean_input($_POST['mother_name']);
    $mother_job = clean_input($_POST['mother_job']);
    $mother_phone = clean_input($_POST['mother_phone']);
    $health_notes = clean_input($_POST['health_notes']);

    if($student_full_name=='' || $stage=='' || $guardian_name=='' || $guardian_phone=='' || $mother_name==''){
        $error = 'يرجى ملء الحقول المطلوبة المحددة بعلامة *';
    } else {
        $safe_student = mysqli_real_escape_string($conn,$student_full_name);
        $safe_phone = mysqli_real_escape_string($conn,$guardian_phone);
        $check = mysqli_query($conn,"SELECT id FROM student_registrations WHERE student_full_name='$safe_student' AND guardian_phone='$safe_phone' LIMIT 1");
        if($check && mysqli_num_rows($check)>0){
            $error = 'تم تسجيل هذا الطالب مسبقاً بنفس رقم ولي الأمر';
        } else {
            $student_photo = '';
            if(isset($_POST['student_photo_base64']) && trim($_POST['student_photo_base64'])!=''){
                $student_photo = sr_save_base64_image($_POST['student_photo_base64'],'student_photos','student_photo',$error);
            }
            if($student_photo=='' && $error==''){
                $student_photo = sr_save_uploaded_image('student_photo_file','student_photos','student_photo',$error);
            }
            if($error==''){
                $sql = "INSERT INTO student_registrations (
                    registration_no, registration_token, student_full_name, gender, birth_date, stage, class_name, previous_school, student_photo,
                    guardian_name, guardian_relation, guardian_phone, guardian_whatsapp, guardian_job, address, map_lat, map_lng, map_link,
                    mother_name, mother_job, mother_phone, health_notes, admin_notes, status, created_at
                ) VALUES (
                    ".sql_text($conn,$registration_no).", ".sql_text($conn,$registration_token).", ".sql_text($conn,$student_full_name).", ".sql_text($conn,$gender).", ".sql_date_or_null($conn,$birth_date).", ".sql_text($conn,$stage).", '', ".sql_text($conn,$previous_school).", ".sql_text($conn,$student_photo).",
                    ".sql_text($conn,$guardian_name).", ".sql_text($conn,$guardian_relation).", ".sql_text($conn,$guardian_phone).", ".sql_text($conn,$guardian_whatsapp).", ".sql_text($conn,$guardian_job).", ".sql_text($conn,$address).", ".sql_text($conn,$map_lat).", ".sql_text($conn,$map_lng).", ".sql_text($conn,$map_link).",
                    ".sql_text($conn,$mother_name).", ".sql_text($conn,$mother_job).", ".sql_text($conn,$mother_phone).", ".sql_text($conn,$health_notes).", '', 'pending', NOW()
                )";
                if(mysqli_query($conn,$sql)){
                    header('Location: student_register.php?success=1');
                    exit();
                } else { $error = 'حدث خطأ أثناء الحفظ: '.mysqli_error($conn); }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>تسجيل طالب جديد</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
:root{--navy:#0b2d4d;--dark:#061b30;--gold:#d7a328;--line:#e2e8f0}*{box-sizing:border-box}body{margin:0;font-family:Cairo,Arial;background:radial-gradient(circle at 12% 8%,rgba(215,163,40,.25),transparent 25%),linear-gradient(135deg,#f8fafc,#eaf0f7,#f6f2e8);color:#132238}.page{width:95%;max-width:1180px;margin:28px auto}.hero{background:linear-gradient(135deg,var(--dark),var(--navy));color:#fff;border-radius:34px;padding:28px;display:grid;grid-template-columns:120px 1fr 240px;gap:20px;align-items:center;box-shadow:0 25px 70px rgba(6,27,48,.23)}.logo{background:#fff;border:3px solid var(--gold);border-radius:28px;padding:12px;width:115px;height:115px}.logo img{width:100%;height:100%;object-fit:contain}.hero h1{margin:0;font-size:34px}.hero p{color:#dbeafe;line-height:1.9}.panel{background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);border-radius:22px;padding:15px;color:#ffe8a3;font-weight:800}.wrap{display:grid;grid-template-columns:260px 1fr;gap:20px;margin-top:20px}.steps{background:rgba(255,255,255,.85);border-radius:28px;padding:18px;box-shadow:0 18px 45px rgba(15,23,42,.08);align-self:start;position:sticky;top:20px}.step{display:flex;gap:10px;align-items:center;background:#fff;border:1px solid #edf2f7;border-radius:18px;padding:12px;margin-bottom:10px;font-weight:900}.num{background:linear-gradient(135deg,#0b2d4d,#164b7d);color:#fff;border-radius:12px;width:34px;height:34px;display:flex;align-items:center;justify-content:center}.card{background:rgba(255,255,255,.92);border-radius:30px;padding:22px;box-shadow:0 22px 60px rgba(15,23,42,.10)}.section{background:#fff;border:1px solid var(--line);border-radius:24px;padding:20px;margin-bottom:18px}.section h2{margin:0 0 15px;color:var(--navy)}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.full{grid-column:1/-1}label{font-weight:900;color:#334155;margin-bottom:7px;display:block}.req{color:#dc2626}input,select,textarea{width:100%;padding:14px;border:1px solid #dbe3ef;border-radius:16px;font-family:Cairo;background:#fff}textarea{min-height:100px}.hint{font-size:12px;color:#64748b;line-height:1.7;margin-top:6px}.photo-box{border:2px dashed var(--gold);background:#fffdf6;border-radius:18px;padding:14px;text-align:center;cursor:pointer;min-height:125px}.preview{width:100px;height:120px;object-fit:cover;border-radius:14px;border:2px solid var(--gold);display:none;margin:8px auto 0}.small-btn,.btn{border:0;border-radius:15px;font-family:Cairo;font-weight:900;cursor:pointer}.small-btn{padding:10px 14px;background:#0b2d4d;color:#fff;margin-top:8px}.actions{display:grid;grid-template-columns:1fr 180px;gap:12px}.btn{padding:17px;font-size:17px}.primary{background:linear-gradient(135deg,#0b2d4d,#123f6d 60%,#d7a328);color:#fff}.light{background:#fff;border:1px solid #dbe3ef;color:#0b2d4d}.alert{background:#fee2e2;color:#991b1b;border:1px solid #fecaca;padding:14px;border-radius:16px;font-weight:900;margin-bottom:15px}.alert.success{background:#dcfce7;color:#166534;border-color:#bbf7d0}.modal{display:none;position:fixed;inset:0;background:rgba(6,27,48,.72);z-index:9999;align-items:center;justify-content:center;padding:15px}.modal.show{display:flex}.modal-card{background:#fff;border-radius:26px;padding:18px;width:100%;max-width:850px}.modal-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}.close{border:0;background:#fee2e2;color:#991b1b;border-radius:12px;padding:8px 12px;font-weight:900}#map{height:420px;border-radius:18px}.camera-video{width:100%;max-height:430px;background:#111;border-radius:18px}.splash{position:fixed;inset:0;z-index:10000;background:linear-gradient(135deg,var(--dark),var(--navy));display:flex;align-items:center;justify-content:center;animation:hide .9s ease 1.1s forwards}.splash img{width:130px;height:130px;background:#fff;border-radius:30px;padding:12px;border:3px solid var(--gold)}@keyframes hide{to{opacity:0;visibility:hidden}}
@media(max-width:900px){.hero,.wrap{grid-template-columns:1fr;text-align:center}.logo{margin:auto}.grid{grid-template-columns:1fr}.steps{position:relative}.actions{grid-template-columns:1fr}}
</style></head><body>
<div class="splash"><img src="/sy/school_system/logo.png" alt="شعار المدرسة"></div>
<div class="page"><div class="hero"><div class="logo"><img src="/sy/school_system/logo.png"></div><div><h1>استمارة تسجيل طالب جديد</h1><p>يرجى إدخال بيانات الطالب بدقة، وبعد الإرسال ستصل المعلومات مباشرة إلى لوحة الإدارة.</p></div><div class="panel">ثانوية الأوائل الأهلية للبنين</div></div>
<div class="wrap"><div class="steps"><h3>مراحل ملء الاستمارة</h3><div class="step"><span class="num">1</span>بيانات الطالب</div><div class="step"><span class="num">2</span>ولي الأمر</div><div class="step"><span class="num">3</span>بيانات الأم</div><div class="step"><span class="num">4</span>ملاحظات</div></div>
<div class="card"><?php if($success!=''){ ?><div class="alert success"><?php echo h($success); ?></div><?php } ?><?php if($error!=''){ ?><div class="alert"><?php echo h($error); ?></div><?php } ?><form method="POST" enctype="multipart/form-data">
<div class="section"><h2>1. بيانات الطالب الأساسية</h2><div class="grid"><div class="full"><label>اسم الطالب الرباعي <span class="req">*</span></label><input name="student_full_name" required value="<?php echo old_value('student_full_name'); ?>"></div><div><label>المرحلة <span class="req">*</span></label><select name="stage" required><option value="">اختر</option><option value="أول متوسط" <?php echo is_selected('stage','أول متوسط'); ?>>أول متوسط</option><option value="ثاني متوسط" <?php echo is_selected('stage','ثاني متوسط'); ?>>ثاني متوسط</option><option value="ثالث متوسط" <?php echo is_selected('stage','ثالث متوسط'); ?>>ثالث متوسط</option><option value="رابع علمي" <?php echo is_selected('stage','رابع علمي'); ?>>رابع علمي</option><option value="خامس علمي" <?php echo is_selected('stage','خامس علمي'); ?>>خامس علمي</option><option value="سادس علمي" <?php echo is_selected('stage','سادس علمي'); ?>>سادس علمي</option></select></div><div><label>الجنس</label><select name="gender"><option value="">اختر</option><option value="ذكر" <?php echo is_selected('gender','ذكر'); ?>>ذكر</option><option value="أنثى" <?php echo is_selected('gender','أنثى'); ?>>أنثى</option></select></div><div><label>تاريخ الميلاد</label><input type="date" name="birth_date" value="<?php echo old_value('birth_date'); ?>"></div><div><label>صورة الطالب <span class="hint">اختياري</span></label><div class="photo-box" onclick="openPhotoModal()">📷 التقاط صورة الطالب<div class="hint">خلفية بيضاء وإضاءة واضحة</div><img id="studentPhotoPreview" class="preview"></div><input type="hidden" name="student_photo_base64" id="student_photo_base64"><input type="file" name="student_photo_file" id="student_photo_file" accept="image/*" capture="user" style="display:none" onchange="previewStudentFile(this)"><button type="button" class="small-btn" onclick="document.getElementById('student_photo_file').click()">اختيار صورة</button></div><div class="full"><label>المدرسة السابقة</label><input name="previous_school" value="<?php echo old_value('previous_school'); ?>"></div></div></div>
<div class="section"><h2>2. بيانات ولي الأمر</h2><div class="grid"><div><label>اسم ولي الأمر <span class="req">*</span></label><input name="guardian_name" required value="<?php echo old_value('guardian_name'); ?>"></div><div><label>صلة القرابة</label><select name="guardian_relation"><option value="">اختر</option><option value="الأب" <?php echo is_selected('guardian_relation','الأب'); ?>>الأب</option><option value="الأم" <?php echo is_selected('guardian_relation','الأم'); ?>>الأم</option><option value="الأخ" <?php echo is_selected('guardian_relation','الأخ'); ?>>الأخ</option><option value="العم" <?php echo is_selected('guardian_relation','العم'); ?>>العم</option><option value="الخال" <?php echo is_selected('guardian_relation','الخال'); ?>>الخال</option></select></div><div><label>رقم هاتف ولي الأمر <span class="req">*</span></label><input name="guardian_phone" required value="<?php echo old_value('guardian_phone'); ?>"></div><div><label>رقم الواتساب</label><input name="guardian_whatsapp" value="<?php echo old_value('guardian_whatsapp'); ?>"></div><div><label>عمل ولي الأمر</label><input name="guardian_job" value="<?php echo old_value('guardian_job'); ?>"></div><div><label>عنوان السكن</label><input name="address" value="<?php echo old_value('address'); ?>"></div><div class="full"><label>العنوان على الخريطة <span class="hint">اختياري</span></label><input type="hidden" name="map_lat" id="map_lat"><input type="hidden" name="map_lng" id="map_lng"><input type="hidden" name="map_link" id="map_link"><button type="button" class="small-btn" onclick="openMapModal()">تحديد دبوس المنزل</button><div id="mapSelectedText" class="hint">لم يتم تحديد الموقع.</div></div></div></div>
<div class="section"><h2>3. بيانات الأم</h2><div class="grid"><div><label>اسم الأم <span class="req">*</span></label><input name="mother_name" required value="<?php echo old_value('mother_name'); ?>"></div><div><label>عمل الأم</label><input name="mother_job" value="<?php echo old_value('mother_job'); ?>"></div><div><label>رقم هاتف الأم</label><input name="mother_phone" value="<?php echo old_value('mother_phone'); ?>"></div></div></div>
<div class="section"><h2>4. ملاحظات إضافية</h2><textarea name="health_notes" placeholder="ملاحظات صحية أو إدارية"><?php echo old_value('health_notes'); ?></textarea></div>
<div class="actions"><button class="btn primary" type="submit">إرسال معلومات التسجيل</button><button class="btn light" type="reset">مسح</button></div></form></div></div></div>
<div class="modal" id="photoModal"><div class="modal-card"><div class="modal-head"><b>التقاط صورة الطالب</b><button class="close" onclick="closePhotoModal()" type="button">إغلاق</button></div><p class="hint">الصورة اختيارية. يفضل خلفية بيضاء.</p><video id="photoVideo" class="camera-video" autoplay playsinline></video><canvas id="photoCanvas" style="display:none"></canvas><button type="button" class="small-btn" onclick="captureStudentPhoto()">التقاط</button><button type="button" class="small-btn" onclick="closePhotoModal()">اعتماد</button></div></div>
<div class="modal" id="mapModal"><div class="modal-card"><div class="modal-head"><b>تحديد موقع المنزل</b><button class="close" onclick="closeMapModal()" type="button">إغلاق</button></div><div id="map"></div><button type="button" class="small-btn" onclick="useMyLocation()">موقعي الحالي</button><button type="button" class="small-btn" onclick="closeMapModal()">اعتماد الموقع</button></div></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script><script>
var photoStream=null;function openPhotoModal(){document.getElementById('photoModal').className='modal show';var v=document.getElementById('photoVideo');if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){navigator.mediaDevices.getUserMedia({video:true,audio:false}).then(function(s){photoStream=s;v.srcObject=s;}).catch(function(){alert('لم يتم فتح الكاميرا. اختر صورة من الجهاز.');});}}
function closePhotoModal(){document.getElementById('photoModal').className='modal';if(photoStream){var t=photoStream.getTracks();for(var i=0;i<t.length;i++){t[i].stop();}photoStream=null;}}
function captureStudentPhoto(){var v=document.getElementById('photoVideo'),c=document.getElementById('photoCanvas');if(!v.videoWidth){alert('الكاميرا غير جاهزة');return;}c.width=v.videoWidth;c.height=v.videoHeight;c.getContext('2d').drawImage(v,0,0,c.width,c.height);var d=c.toDataURL('image/jpeg',.9);document.getElementById('student_photo_base64').value=d;var img=document.getElementById('studentPhotoPreview');img.src=d;img.style.display='block';}
function previewStudentFile(input){if(input.files&&input.files[0]){var r=new FileReader();r.onload=function(e){var img=document.getElementById('studentPhotoPreview');img.src=e.target.result;img.style.display='block';document.getElementById('student_photo_base64').value='';};r.readAsDataURL(input.files[0]);}}
var mapObj=null,mapMarker=null;function openMapModal(){document.getElementById('mapModal').className='modal show';setTimeout(function(){if(!mapObj){mapObj=L.map('map').setView([36.34,43.13],12);L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19}).addTo(mapObj);mapObj.on('click',function(e){setMapPoint(e.latlng.lat,e.latlng.lng);});}mapObj.invalidateSize();},200);}function closeMapModal(){document.getElementById('mapModal').className='modal';}function setMapPoint(lat,lng){document.getElementById('map_lat').value=lat;document.getElementById('map_lng').value=lng;var link='https://www.google.com/maps?q='+lat+','+lng;document.getElementById('map_link').value=link;document.getElementById('mapSelectedText').innerHTML='تم تحديد الموقع: <a href="'+link+'" target="_blank">فتح الخريطة</a>';if(mapMarker){mapObj.removeLayer(mapMarker);}mapMarker=L.marker([lat,lng]).addTo(mapObj);}function useMyLocation(){if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(p){setMapPoint(p.coords.latitude,p.coords.longitude);mapObj.setView([p.coords.latitude,p.coords.longitude],16);},function(){alert('تعذر تحديد الموقع.');});}}
</script></body></html>
