<?php
session_start();
require_once __DIR__ . '/parent_portal_common.php';
$conn = pp_connect();
parent_portal_install($conn);

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    if ($action == 'create') {
        $student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
        $guardian_name = isset($_POST['guardian_name']) ? trim($_POST['guardian_name']) : '';
        $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';

        if ($student_id <= 0 || $username == '' || $password == '') {
            $error = 'يرجى اختيار الطالب وكتابة اسم المستخدم وكلمة المرور.';
        } else {
            $u = pp_clean($conn, $username);
            $check = mysqli_query($conn, "SELECT id FROM parent_accounts WHERE username='$u' LIMIT 1");
            if ($check && mysqli_num_rows($check) > 0) {
                $error = 'اسم المستخدم موجود مسبقاً.';
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = mysqli_prepare($conn, "INSERT INTO parent_accounts (student_id, guardian_name, phone, username, password_hash, is_active) VALUES (?, ?, ?, ?, ?, 1)");
                if ($stmt) {
                    mysqli_stmt_bind_param($stmt, 'issss', $student_id, $guardian_name, $phone, $username, $hash);
                    if (mysqli_stmt_execute($stmt)) $success = 'تم إنشاء حساب ولي الأمر بنجاح.';
                    else $error = 'حدث خطأ أثناء الحفظ: ' . mysqli_stmt_error($stmt);
                    mysqli_stmt_close($stmt);
                } else $error = 'حدث خطأ في تجهيز الحفظ: ' . mysqli_error($conn);
            }
        }
    }

    if ($action == 'toggle') {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $new_status = isset($_POST['new_status']) ? intval($_POST['new_status']) : 0;
        if ($id > 0) {
            if (mysqli_query($conn, "UPDATE parent_accounts SET is_active='$new_status' WHERE id='$id'")) $success = 'تم تحديث حالة الحساب.';
            else $error = 'حدث خطأ أثناء تحديث الحالة: ' . mysqli_error($conn);
        }
    }

    if ($action == 'reset_password') {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
        if ($id <= 0 || $new_password == '') {
            $error = 'يرجى كتابة كلمة المرور الجديدة.';
        } else {
            $hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = mysqli_prepare($conn, "UPDATE parent_accounts SET password_hash=? WHERE id=?");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, 'si', $hash, $id);
                if (mysqli_stmt_execute($stmt)) $success = 'تم تغيير كلمة المرور بنجاح.';
                else $error = 'حدث خطأ أثناء تغيير كلمة المرور: ' . mysqli_stmt_error($stmt);
                mysqli_stmt_close($stmt);
            }
        }
    }
}

$q = isset($_GET['q']) ? pp_clean($conn, $_GET['q']) : '';
$where = " WHERE 1=1 ";
if ($q != '') {
    $where .= " AND (pa.username LIKE '%$q%' OR pa.guardian_name LIKE '%$q%' OR pa.phone LIKE '%$q%' OR s.name LIKE '%$q%') ";
}

$students = mysqli_query($conn, "SELECT id, name, stage, class FROM students ORDER BY stage ASC, class ASC, name ASC");
$accounts = mysqli_query($conn, "
    SELECT pa.*, s.name AS student_name, s.stage, s.class
    FROM parent_accounts pa
    LEFT JOIN students s ON s.id = pa.student_id
    $where
    ORDER BY pa.id DESC
");
$count_accounts_q = mysqli_query($conn, "SELECT COUNT(*) c, SUM(is_active=1) active_count FROM parent_accounts");
$total_accounts = 0; $active_accounts = 0;
if ($count_accounts_q && mysqli_num_rows($count_accounts_q) > 0) {
    $cr = mysqli_fetch_assoc($count_accounts_q);
    $total_accounts = intval($cr['c']);
    $active_accounts = intval($cr['active_count']);
}
?>
<!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"><style>
:root{--navy:#0b2d4d;--dark:#061b30;--gold:#d7a328;--line:#e2e8f0;--muted:#64748b;--green:#16a34a;--red:#dc2626}*{box-sizing:border-box}body{margin:0;font-family:Cairo,Arial;background:radial-gradient(circle at 10% 10%,rgba(215,163,40,.20),transparent 25%),linear-gradient(135deg,#f8fafc,#eef4fb,#f7f2e8);color:#132238}.container{width:95%;max-width:1280px;margin:25px auto}.hero{background:linear-gradient(135deg,var(--dark),var(--navy));color:#fff;border-radius:30px;padding:24px;display:grid;grid-template-columns:90px 1fr auto;gap:16px;align-items:center;box-shadow:0 25px 70px rgba(6,27,48,.22)}.logo{width:88px;height:88px;background:#fff;border:3px solid var(--gold);border-radius:24px;padding:9px}.logo img{width:100%;height:100%;object-fit:contain}.hero h1{margin:0;font-size:30px}.hero p{margin:6px 0 0;color:#dbeafe}.top-link{background:#fff7df;color:#6e5207;text-decoration:none;border-radius:15px;padding:12px 16px;font-weight:900}.stats{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin:18px 0}.stat{background:#fff;border-radius:22px;padding:18px;box-shadow:0 16px 36px rgba(15,23,42,.07)}.stat span{color:var(--muted);font-weight:800}.stat b{display:block;font-size:32px;color:var(--navy)}.card{background:#fff;border-radius:26px;padding:20px;box-shadow:0 18px 42px rgba(15,23,42,.08);margin-bottom:18px}.card h2{margin:0 0 14px;color:var(--navy)}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:13px}.field label{display:block;font-weight:900;margin-bottom:7px;color:#334155}.field input,.field select{width:100%;padding:13px;border:1px solid #dbe3ef;border-radius:16px;font-family:Cairo;outline:none}.field input:focus,.field select:focus{border-color:var(--gold);box-shadow:0 0 0 4px rgba(215,163,40,.14)}.btn{border:none;border-radius:16px;padding:13px 16px;font-family:Cairo;font-weight:900;cursor:pointer}.btn-main{background:linear-gradient(135deg,var(--navy),#174f80,var(--gold));color:#fff}.btn-blue{background:#eef5ff;color:#0b2d4d;border:1px solid #d9e7f5}.btn-green{background:#dcfce7;color:#166534}.btn-red{background:#fee2e2;color:#991b1b}.alert{padding:14px;border-radius:16px;text-align:center;font-weight:900;margin-bottom:15px}.success{background:#dcfce7;color:#166534}.error{background:#fee2e2;color:#991b1b}.search-row{display:grid;grid-template-columns:1fr 130px;gap:10px}.table-wrap{overflow-x:auto;border:1px solid #edf2f7;border-radius:20px}table{width:100%;border-collapse:collapse;min-width:900px}th,td{text-align:center;padding:11px;border-bottom:1px solid #edf2f7;white-space:nowrap}th{background:var(--navy);color:#fff}.badge{display:inline-block;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:900}.active{background:#dcfce7;color:#166534}.off{background:#fee2e2;color:#991b1b}.modal{display:none;position:fixed;inset:0;background:rgba(6,27,48,.58);z-index:999;align-items:center;justify-content:center;padding:16px}.modal.show{display:flex}.modal-box{background:#fff;border-radius:24px;padding:22px;max-width:460px;width:100%;box-shadow:0 30px 90px rgba(0,0,0,.3)}.modal-box h3{margin:0 0 12px;color:var(--navy)}@media(max-width:850px){.hero{grid-template-columns:1fr;text-align:center}.logo{margin:auto}.stats,.grid,.search-row{grid-template-columns:1fr}}
</style></head><body><div class="container">
<div class="hero"><div class="logo"><img src="/sy/school_system/logo.png" alt="logo"></div><div><h1>إدارة حسابات أولياء الأمور</h1><p>إنشاء وتفعيل وإدارة حسابات أولياء الأمور وربطها بالطلبة.</p></div><a class="top-link" href="admin_dashboard.php">لوحة الإدارة</a></div>
<div class="stats"><div class="stat"><span>إجمالي الحسابات</span><b><?php echo $total_accounts; ?></b></div><div class="stat"><span>الحسابات المفعلة</span><b><?php echo $active_accounts; ?></b></div></div>
<?php if($success!=''){ ?><div class="alert success"><?php echo h($success); ?></div><?php } ?><?php if($error!=''){ ?><div class="alert error"><?php echo h($error); ?></div><?php } ?>
<div class="card"><h2>إنشاء حساب جديد</h2><form method="POST"><input type="hidden" name="action" value="create"><div class="grid"><div class="field"><label>اختر الطالب</label><select name="student_id" required><option value="">اختر الطالب</option><?php if($students){ while($s=mysqli_fetch_assoc($students)){ ?><option value="<?php echo intval($s['id']); ?>"><?php echo h($s['name'].' - '.$s['stage'].' - '.$s['class']); ?></option><?php }} ?></select></div><div class="field"><label>اسم ولي الأمر</label><input type="text" name="guardian_name" placeholder="اسم ولي الأمر"></div><div class="field"><label>رقم الهاتف</label><input type="text" name="phone" placeholder="07xxxxxxxxx"></div><div class="field"><label>اسم المستخدم</label><input type="text" name="username" required placeholder="مثال: parent_1001"></div><div class="field"><label>كلمة المرور</label><input type="text" name="password" required placeholder="مثال: 123456"></div></div><br><button class="btn btn-main" type="submit">إنشاء الحساب</button></form></div>
<div class="card"><h2>الحسابات الحالية</h2><form method="GET" class="search-row"><input type="text" name="q" value="<?php echo pp_get('q'); ?>" placeholder="بحث باسم الطالب أو ولي الأمر أو الهاتف أو اسم المستخدم"><button class="btn btn-main" type="submit">بحث</button></form><br><div class="table-wrap"><table><tr><th>#</th><th>الطالب</th><th>المرحلة</th><th>الشعبة</th><th>ولي الأمر</th><th>الهاتف</th><th>اسم المستخدم</th><th>الحالة</th><th>إجراءات</th></tr><?php if($accounts && mysqli_num_rows($accounts)>0){ while($a=mysqli_fetch_assoc($accounts)){ ?><tr><td><?php echo intval($a['id']); ?></td><td><?php echo h($a['student_name']); ?></td><td><?php echo h($a['stage']); ?></td><td><?php echo h($a['class']); ?></td><td><?php echo h($a['guardian_name']); ?></td><td><?php echo h($a['phone']); ?></td><td><b><?php echo h($a['username']); ?></b></td><td><span class="badge <?php echo intval($a['is_active'])==1?'active':'off'; ?>"><?php echo intval($a['is_active'])==1?'مفعل':'متوقف'; ?></span></td><td><form method="POST" style="display:inline"><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?php echo intval($a['id']); ?>"><input type="hidden" name="new_status" value="<?php echo intval($a['is_active'])==1?0:1; ?>"><button class="btn <?php echo intval($a['is_active'])==1?'btn-red':'btn-green'; ?>" type="submit"><?php echo intval($a['is_active'])==1?'إيقاف':'تفعيل'; ?></button></form> <button class="btn btn-blue" type="button" onclick="openReset('<?php echo intval($a['id']); ?>','<?php echo h($a['username']); ?>')">تغيير كلمة المرور</button></td></tr><?php }} else { ?><tr><td colspan="9">لا توجد حسابات.</td></tr><?php } ?></table></div></div>
</div><div class="modal" id="resetModal"><div class="modal-box"><h3>تغيير كلمة المرور</h3><form method="POST"><input type="hidden" name="action" value="reset_password"><input type="hidden" name="id" id="resetId"><div class="field"><label>الحساب</label><input type="text" id="resetUser" readonly></div><div class="field"><label>كلمة المرور الجديدة</label><input type="text" name="new_password" required></div><button class="btn btn-main" type="submit">حفظ كلمة المرور</button> <button class="btn btn-blue" type="button" onclick="closeReset()">إلغاء</button></form></div></div><script>function openReset(id,u){document.getElementById('resetId').value=id;document.getElementById('resetUser').value=u;document.getElementById('resetModal').className='modal show'}function closeReset(){document.getElementById('resetModal').className='modal'}</script></body></html>
