<?php
/*
  registration_helpers.php
  دوال مشتركة لتسجيل الطلبة + الزي والكتب
  متوافق مع PHP القديم:
  - بدون ??
  - بدون []
  - بدون mysqli_stmt_get_result()

  تحديث مهم:
  - تم إضافة جدول مستقل school_supply_students
  - إدارة الزي والكتب تعتمد على الطلبة المسجلين فقط من student_registrations
  - لا تعتمد على جدول students القديم نهائياً
*/

function sr_connect() {
    if (file_exists(__DIR__ . "/includes/config.php")) {
        include(__DIR__ . "/includes/config.php");
    } elseif (file_exists(__DIR__ . "/db.php")) {
        include(__DIR__ . "/db.php");
    } else {
        die("لم يتم العثور على ملف الاتصال بقاعدة البيانات.");
    }

    if (!isset($conn) || !$conn) {
        die("فشل الاتصال بقاعدة البيانات.");
    }

    mysqli_set_charset($conn, "utf8mb4");
    return $conn;
}

function h($value) {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function clean_input($value) {
    return isset($value) ? trim($value) : "";
}

function table_exists($conn, $table) {
    $table = mysqli_real_escape_string($conn, $table);
    $q = mysqli_query($conn, "SHOW TABLES LIKE '$table'");
    return ($q && mysqli_num_rows($q) > 0);
}

function column_exists($conn, $table, $column) {
    if (!table_exists($conn, $table)) {
        return false;
    }

    $table = mysqli_real_escape_string($conn, $table);
    $column = mysqli_real_escape_string($conn, $column);

    $q = mysqli_query($conn, "SHOW COLUMNS FROM `$table` LIKE '$column'");
    return ($q && mysqli_num_rows($q) > 0);
}

function add_column_if_missing($conn, $table, $column, $definition) {
    if (!column_exists($conn, $table, $column)) {
        $table = mysqli_real_escape_string($conn, $table);
        $column = mysqli_real_escape_string($conn, $column);
        mysqli_query($conn, "ALTER TABLE `$table` ADD `$column` $definition");
    }
}

function sr_mkdir($dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
}

function sr_install($conn) {
    if (!table_exists($conn, "student_registrations")) {
        mysqli_query($conn, "
            CREATE TABLE student_registrations (
                id INT(11) NOT NULL AUTO_INCREMENT,
                registration_no VARCHAR(50) DEFAULT NULL,
                registration_token VARCHAR(80) DEFAULT NULL,

                student_full_name VARCHAR(255) NOT NULL,
                gender VARCHAR(20) DEFAULT NULL,
                birth_date DATE DEFAULT NULL,
                stage VARCHAR(100) NOT NULL,
                class_name VARCHAR(50) DEFAULT NULL,
                previous_school VARCHAR(255) DEFAULT NULL,
                student_photo VARCHAR(255) DEFAULT NULL,

                mother_name VARCHAR(255) DEFAULT NULL,
                mother_job VARCHAR(150) DEFAULT NULL,
                mother_phone VARCHAR(30) DEFAULT NULL,

                guardian_name VARCHAR(255) NOT NULL,
                guardian_relation VARCHAR(100) DEFAULT NULL,
                guardian_phone VARCHAR(30) NOT NULL,
                guardian_whatsapp VARCHAR(30) DEFAULT NULL,
                guardian_job VARCHAR(150) DEFAULT NULL,
                address TEXT DEFAULT NULL,

                map_lat VARCHAR(60) DEFAULT NULL,
                map_lng VARCHAR(60) DEFAULT NULL,
                map_link TEXT DEFAULT NULL,

                health_notes TEXT DEFAULT NULL,
                admin_notes TEXT DEFAULT NULL,
                status VARCHAR(30) NOT NULL DEFAULT 'pending',

                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

                PRIMARY KEY (id),
                UNIQUE KEY registration_no (registration_no),
                KEY registration_token (registration_token)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    add_column_if_missing($conn, "student_registrations", "registration_no", "VARCHAR(50) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "registration_token", "VARCHAR(80) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "student_full_name", "VARCHAR(255) NOT NULL");
    add_column_if_missing($conn, "student_registrations", "gender", "VARCHAR(20) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "birth_date", "DATE DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "stage", "VARCHAR(100) NOT NULL");
    add_column_if_missing($conn, "student_registrations", "class_name", "VARCHAR(50) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "previous_school", "VARCHAR(255) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "student_photo", "VARCHAR(255) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "mother_name", "VARCHAR(255) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "mother_job", "VARCHAR(150) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "mother_phone", "VARCHAR(30) DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "guardian_name", "VARCHAR(255) NOT NULL");
    add_column_if_missing($conn, "student_registrations", "guardian_phone", "VARCHAR(30) NOT NULL");
    add_column_if_missing($conn, "student_registrations", "address", "TEXT DEFAULT NULL");
    add_column_if_missing($conn, "student_registrations", "status", "VARCHAR(30) NOT NULL DEFAULT 'pending'");
    add_column_if_missing($conn, "student_registrations", "created_at", "TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP");

    @mysqli_query($conn, "ALTER TABLE student_registrations MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
    @mysqli_query($conn, "ALTER TABLE student_registrations MODIFY status VARCHAR(30) NOT NULL DEFAULT 'pending'");

    if (!table_exists($conn, "school_supply_inventory")) {
        mysqli_query($conn, "
            CREATE TABLE school_supply_inventory (
                id INT(11) NOT NULL AUTO_INCREMENT,
                item_category VARCHAR(30) NOT NULL DEFAULT 'uniform',
                item_name VARCHAR(150) NOT NULL,
                size_label VARCHAR(50) DEFAULT '',
                initial_qty INT(11) NOT NULL DEFAULT 0,
                notes TEXT DEFAULT NULL,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                UNIQUE KEY item_unique (item_category, item_name, size_label)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    /*
      جدول مستقل للطلبة الذين يظهرون فقط في إدارة الزي والكتب.
      يتم ملؤه من student_registrations، ولا يعتمد على جدول students القديم.
    */
    if (!table_exists($conn, "school_supply_students")) {
        mysqli_query($conn, "
            CREATE TABLE school_supply_students (
                id INT(11) NOT NULL AUTO_INCREMENT,
                registration_id INT(11) DEFAULT NULL,
                registration_no VARCHAR(50) DEFAULT NULL,
                student_name VARCHAR(255) NOT NULL,
                stage VARCHAR(100) DEFAULT NULL,
                class_name VARCHAR(50) DEFAULT NULL,
                guardian_name VARCHAR(255) DEFAULT NULL,
                guardian_phone VARCHAR(30) DEFAULT NULL,
                status VARCHAR(30) NOT NULL DEFAULT 'active',
                source VARCHAR(30) NOT NULL DEFAULT 'registration',
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                UNIQUE KEY registration_id (registration_id),
                KEY student_name (student_name),
                KEY stage (stage),
                KEY class_name (class_name)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    add_column_if_missing($conn, "school_supply_students", "registration_id", "INT(11) DEFAULT NULL");
    add_column_if_missing($conn, "school_supply_students", "registration_no", "VARCHAR(50) DEFAULT NULL");
    add_column_if_missing($conn, "school_supply_students", "student_name", "VARCHAR(255) NOT NULL");
    add_column_if_missing($conn, "school_supply_students", "stage", "VARCHAR(100) DEFAULT NULL");
    add_column_if_missing($conn, "school_supply_students", "class_name", "VARCHAR(50) DEFAULT NULL");
    add_column_if_missing($conn, "school_supply_students", "guardian_name", "VARCHAR(255) DEFAULT NULL");
    add_column_if_missing($conn, "school_supply_students", "guardian_phone", "VARCHAR(30) DEFAULT NULL");
    add_column_if_missing($conn, "school_supply_students", "status", "VARCHAR(30) NOT NULL DEFAULT 'active'");
    add_column_if_missing($conn, "school_supply_students", "source", "VARCHAR(30) NOT NULL DEFAULT 'registration'");

    /*
      جدول جديد للتسليم يعتمد على school_supply_students وليس students القديم.
      تركنا جدول school_supply_distribution القديم كما هو بدون استخدامه هنا حتى لا يتأثر النظام السابق.
    */
    if (!table_exists($conn, "school_supply_distribution_reg")) {
        mysqli_query($conn, "
            CREATE TABLE school_supply_distribution_reg (
                id INT(11) NOT NULL AUTO_INCREMENT,
                supply_student_id INT(11) NOT NULL,
                registration_id INT(11) DEFAULT NULL,
                inventory_id INT(11) NOT NULL,
                item_category VARCHAR(30) NOT NULL,
                item_name VARCHAR(150) NOT NULL,
                size_label VARCHAR(50) DEFAULT '',
                qty INT(11) NOT NULL DEFAULT 1,
                notes TEXT DEFAULT NULL,
                delivered_by VARCHAR(150) DEFAULT NULL,
                delivered_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY supply_student_id (supply_student_id),
                KEY registration_id (registration_id),
                KEY inventory_id (inventory_id)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    sr_seed_uniform_inventory($conn);
    sr_sync_registered_students_to_supply($conn);
}

function sr_sync_registered_students_to_supply($conn) {
    if (!table_exists($conn, "student_registrations") || !table_exists($conn, "school_supply_students")) {
        return;
    }

    $q = mysqli_query($conn, "
        SELECT id, registration_no, student_full_name, stage, class_name, guardian_name, guardian_phone, status
        FROM student_registrations
        WHERE student_full_name <> ''
        AND status <> 'rejected'
        ORDER BY id ASC
    ");

    if (!$q) {
        return;
    }

    while ($r = mysqli_fetch_assoc($q)) {
        $registration_id = intval($r['id']);
        $registration_no = mysqli_real_escape_string($conn, $r['registration_no']);
        $student_name    = mysqli_real_escape_string($conn, $r['student_full_name']);
        $stage           = mysqli_real_escape_string($conn, $r['stage']);
        $class_name      = mysqli_real_escape_string($conn, $r['class_name']);
        $guardian_name   = mysqli_real_escape_string($conn, $r['guardian_name']);
        $guardian_phone  = mysqli_real_escape_string($conn, $r['guardian_phone']);

        $check = mysqli_query($conn, "SELECT id FROM school_supply_students WHERE registration_id='$registration_id' LIMIT 1");

        if ($check && mysqli_num_rows($check) > 0) {
            mysqli_query($conn, "
                UPDATE school_supply_students
                SET registration_no='$registration_no',
                    student_name='$student_name',
                    stage='$stage',
                    class_name='$class_name',
                    guardian_name='$guardian_name',
                    guardian_phone='$guardian_phone',
                    status='active'
                WHERE registration_id='$registration_id'
                LIMIT 1
            ");
        } else {
            mysqli_query($conn, "
                INSERT INTO school_supply_students
                (registration_id, registration_no, student_name, stage, class_name, guardian_name, guardian_phone, status, source)
                VALUES
                ('$registration_id', '$registration_no', '$student_name', '$stage', '$class_name', '$guardian_name', '$guardian_phone', 'active', 'registration')
            ");
        }
    }
}

function sr_seed_uniform_inventory($conn) {
    $q = mysqli_query($conn, "SELECT COUNT(*) AS c FROM school_supply_inventory WHERE item_category='uniform'");
    $count = 0;

    if ($q && mysqli_num_rows($q) > 0) {
        $r = mysqli_fetch_assoc($q);
        $count = intval($r['c']);
    }

    if ($count > 0) {
        return;
    }

    $items = array(
        array('تيشيرت','5',102), array('تيشيرت','6',25), array('تيشيرت','7',40), array('تيشيرت','8',2), array('تيشيرت','9',24), array('تيشيرت','10',18), array('تيشيرت','11',9), array('تيشيرت','12',17), array('تيشيرت','13',0), array('تيشيرت','14',0), array('تيشيرت','3X',0),

        array('قمصلة','5',104), array('قمصلة','6',49), array('قمصلة','7',36), array('قمصلة','8',18), array('قمصلة','9',9), array('قمصلة','10',18), array('قمصلة','11',8), array('قمصلة','12',105), array('قمصلة','13',47), array('قمصلة','14',0), array('قمصلة','3X',0),

        array('بلوز','5',77), array('بلوز','6',41), array('بلوز','7',0), array('بلوز','8',5), array('بلوز','9',13), array('بلوز','10',3), array('بلوز','11',23), array('بلوز','12',46), array('بلوز','13',0), array('بلوز','14',0), array('بلوز','3X',0),

        array('زي رياضي','S',0), array('زي رياضي','M',27), array('زي رياضي','L',2), array('زي رياضي','XL',0), array('زي رياضي','2XL',0), array('زي رياضي','3XL',8), array('زي رياضي','8',34), array('زي رياضي','10',34), array('زي رياضي','11',12)
    );

    $i = 0;
    for ($i=0; $i<count($items); $i++) {
        $name = mysqli_real_escape_string($conn, $items[$i][0]);
        $size = mysqli_real_escape_string($conn, $items[$i][1]);
        $qty = intval($items[$i][2]);

        mysqli_query($conn, "
            INSERT INTO school_supply_inventory (item_category, item_name, size_label, initial_qty, notes)
            VALUES ('uniform', '$name', '$size', '$qty', 'رصيد افتتاحي من جرد الزي 2027')
        ");
    }
}

function sr_generate_token() {
    return md5(uniqid(mt_rand(), true));
}

function sr_generate_registration_no($conn) {
    $year = date('Y');

    do {
        $number = 'REG-' . $year . '-' . date('mdHis') . '-' . rand(10, 99);
        $safe = mysqli_real_escape_string($conn, $number);
        $q = mysqli_query($conn, "SELECT id FROM student_registrations WHERE registration_no='$safe' LIMIT 1");
        $exists = ($q && mysqli_num_rows($q) > 0);
    } while ($exists);

    return $number;
}

function sql_text($conn, $value) {
    return "'" . mysqli_real_escape_string($conn, trim($value)) . "'";
}

function sql_date_or_null($conn, $value) {
    $value = trim($value);

    if ($value == "") {
        return "NULL";
    }

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
        return "NULL";
    }

    return "'" . mysqli_real_escape_string($conn, $value) . "'";
}

function old_value($name) {
    if (isset($_POST[$name])) {
        return h($_POST[$name]);
    }
    return "";
}

function is_selected($name, $value) {
    if (isset($_POST[$name]) && $_POST[$name] == $value) {
        return "selected";
    }
    return "";
}

function sr_save_uploaded_image($field_name, $sub_dir, $prefix, &$error) {
    if (!isset($_FILES[$field_name]) || !isset($_FILES[$field_name]['tmp_name']) || $_FILES[$field_name]['tmp_name'] == "") {
        return "";
    }

    if (!is_uploaded_file($_FILES[$field_name]['tmp_name'])) {
        return "";
    }

    if ($_FILES[$field_name]['error'] != 0) {
        $error = "حدث خطأ أثناء رفع الصورة: " . $field_name;
        return "";
    }

    if ($_FILES[$field_name]['size'] > 10 * 1024 * 1024) {
        $error = "حجم الصورة كبير جداً. يجب أن لا يتجاوز 10MB.";
        return "";
    }

    $img = @getimagesize($_FILES[$field_name]['tmp_name']);
    if ($img === false) {
        $error = "الملف المرفوع ليس صورة صحيحة: " . $field_name;
        return "";
    }

    $ext = "jpg";
    if ($img[2] == IMAGETYPE_PNG) {
        $ext = "png";
    } elseif ($img[2] == IMAGETYPE_GIF) {
        $ext = "gif";
    } elseif ($img[2] == IMAGETYPE_JPEG) {
        $ext = "jpg";
    }

    $dir = __DIR__ . "/uploads/" . $sub_dir;
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }

    $name = $prefix . "_" . date("YmdHis") . "_" . rand(1000,9999) . "." . $ext;
    $dest = $dir . "/" . $name;

    if (move_uploaded_file($_FILES[$field_name]['tmp_name'], $dest)) {
        return "uploads/" . $sub_dir . "/" . $name;
    }

    $error = "فشل حفظ الصورة على السيرفر.";
    return "";
}

function sr_save_base64_image($base64, $sub_dir, $prefix, &$error) {
    $base64 = trim($base64);

    if ($base64 == "") {
        return "";
    }

    if (!preg_match('/^data:image\/(png|jpeg|jpg);base64,/', $base64, $m)) {
        return "";
    }

    $data = preg_replace('/^data:image\/(png|jpeg|jpg);base64,/', '', $base64);
    $data = str_replace(' ', '+', $data);
    $decoded = base64_decode($data);

    if ($decoded === false) {
        $error = "فشل قراءة الصورة الملتقطة.";
        return "";
    }

    if (strlen($decoded) > 10 * 1024 * 1024) {
        $error = "حجم الصورة الملتقطة كبير جداً.";
        return "";
    }

    $dir = __DIR__ . "/uploads/" . $sub_dir;
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }

    $ext = ($m[1] == "png") ? "png" : "jpg";
    $name = $prefix . "_" . date("YmdHis") . "_" . rand(1000,9999) . "." . $ext;
    $dest = $dir . "/" . $name;

    if (file_put_contents($dest, $decoded)) {
        return "uploads/" . $sub_dir . "/" . $name;
    }

    $error = "فشل حفظ الصورة الملتقطة.";
    return "";
}

function sr_get_registration($conn, $id, $token) {
    $id = intval($id);
    $token = mysqli_real_escape_string($conn, $token);

    $q = mysqli_query($conn, "SELECT * FROM student_registrations WHERE id='$id' AND registration_token='$token' LIMIT 1");

    if ($q && mysqli_num_rows($q) > 0) {
        return mysqli_fetch_assoc($q);
    }

    return false;
}

function sr_status_label($status) {
    if ($status == "accepted") return "مقبول";
    if ($status == "rejected") return "مرفوض";
    return "قيد المراجعة";
}

function sr_status_class($status) {
    if ($status == "accepted") return "accepted";
    if ($status == "rejected") return "rejected";
    return "pending";
}
?>
