<?php
// student_update.php - Fixed version with profile_completed=1 and email confirmation
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// Keep errors out of the page so redirects work
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/uploads/php_errors.log');
error_reporting(E_ALL);

// Capture fatal shutdowns
register_shutdown_function(function(){
  $e = error_get_last();
  if ($e && in_array($e['type'], [E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR])) {
    error_log("FATAL: {$e['message']} in {$e['file']}:{$e['line']}");
    // Ensure clean redirect even on fatal errors
    header("Location: student_success.php");
    exit;
  }
});

// Include required files with error handling
try {
    require 'db.php';
    require 'helpers.php';
    require_student();
} catch (Exception $e) {
    error_log("Required file error: " . $e->getMessage());
    header("Location: student_success.php");
    exit;
}

/* ---------- Helpers ---------- */
function to_int_or_null($v){ if($v===''||$v===null) return null; return (int)$v; }
function ensure_dir($dir, $mode=0775){
  clearstatcache(true,$dir);
  if (is_dir($dir)) return true;
  $parent = dirname($dir);
  if ($parent && $parent!==$dir && !is_dir($parent)) if (!ensure_dir($parent,$mode)) return false;
  $old = umask(0);
  $ok = @mkdir($dir,$mode,true);
  umask($old);
  clearstatcache(true,$dir);
  return $ok || is_dir($dir);
}

/* ---------- CSRF ---------- */
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !verify_csrf($_POST['csrf'] ?? '')) {
  error_log("CSRF validation failed");
  header("Location: student_profile.php?error=csrf_failed");
  exit;
}

$student_id = $_SESSION['student_id'] ?? '';
if ($student_id === '') {
  error_log("No student ID in session");
  header("Location: student_login.php");
  exit;
}

/* ---------- Collect & sanitize ---------- */
$fields = [
  'student_name_eng','email','phone_number','phone_number2','nationality',
  'national_id','guardian_name','guardian_phone_number','guardian_address',
  'date_of_birth','gender','home_address','blood_type','country_id',
  'state_id','locality_id','student_case'
];
$data = [];
foreach ($fields as $f) { $data[$f] = trim($_POST[$f] ?? ''); }
$data['country_id']  = to_int_or_null($data['country_id']);
$data['state_id']    = to_int_or_null($data['state_id']);
$data['locality_id'] = to_int_or_null($data['locality_id']);
$data['gender']      = to_int_or_null($data['gender']);
$agreed_regulations  = isset($_POST['agreed_regulations']) ? 1 : 0;
$self_declare_fit       = isset($_POST['self_declare_fit']) ? 1 : 0;

/* ---------- Update students core fields with profile_completed=1 ---------- */
$stmt = $mysqli1->prepare("
  UPDATE students SET
    student_name_eng = ?, email = ?, phone_number = ?, phone_number2 = ?,
    nationality = ?, national_id = ?, guardian_name = ?, guardian_phone_number = ?,
    guardian_address = ?, date_of_birth = ?, gender = ?, home_address = ?,
    blood_type = ?, country_id = ?, state_id = ?, locality_id = ?,
    student_case = ?, agreed_regulations = ?, self_declare_fit = ?,
    profile_completed = 1
  WHERE student_id = ?
");
if (!$stmt) { 
    error_log('Prepare failed: '.$mysqli1->error); 
    header("Location: student_profile.php?error=update_failed");
    exit;
}

$stmt->bind_param(
  "sssssssssssssiiisiis",
  $data['student_name_eng'], $data['email'], $data['phone_number'], $data['phone_number2'],
  $data['nationality'], $data['national_id'], $data['guardian_name'], $data['guardian_phone_number'],
  $data['guardian_address'], $data['date_of_birth'], $data['gender'], $data['home_address'],
  $data['blood_type'],
  $data['country_id'], $data['state_id'], $data['locality_id'],
  $data['student_case'],
  $agreed_regulations, $self_declare_fit,
  $student_id
);

if (!$stmt->execute()) { 
    error_log('Update failed: '.$stmt->error); 
    header("Location: student_profile.php?error=update_failed");
    exit;
}
$stmt->close();

/* ========= SAVE PERSONAL PHOTO & NATIONAL ID (both) ========= */
$uploadsFs = __DIR__ . '/uploads';
ensure_dir($uploadsFs, 0775);
$MAX = 5 * 1024 * 1024;

/* --- Personal Photo -> uploads/<id>_P.<ext> --- */
if (!empty($_FILES['file_personal_photo']['name']) && $_FILES['file_personal_photo']['error'] === UPLOAD_ERR_OK) {
  $pf  = $_FILES['file_personal_photo'];
  $ext = strtolower(pathinfo($pf['name'], PATHINFO_EXTENSION));
  if (in_array($ext, ['jpg','jpeg','png','webp'], true) && $pf['size'] <= $MAX && is_uploaded_file($pf['tmp_name'])) {

    // clean old variants (case-insensitive)
    foreach (['jpg','jpeg','png','webp','JPG','JPEG','PNG','WEBP'] as $e) { 
      @unlink($uploadsFs . "/{$student_id}_P.$e"); 
    }

    $destFs = $uploadsFs . "/{$student_id}_P.$ext";
    
    if (@move_uploaded_file($pf['tmp_name'], $destFs)) {
      @chmod($destFs,0644);
      error_log("[UPLOAD] Personal photo saved: $destFs");
    } else {
      error_log("[UPLOAD] move failed (personal) to $destFs");
    }
  }
}

/* --- National ID -> uploads/<id>_N.<ext> --- */
if (!empty($_FILES['file_national_id']['name']) && $_FILES['file_national_id']['error'] === UPLOAD_ERR_OK) {
  $nf  = $_FILES['file_national_id'];
  $ext = strtolower(pathinfo($nf['name'], PATHINFO_EXTENSION));
  if (in_array($ext, ['pdf','jpg','jpeg','png','webp'], true) && $nf['size'] <= $MAX && is_uploaded_file($nf['tmp_name'])) {

    // clean old variants (case-insensitive)
    foreach (['pdf','jpg','jpeg','png','webp','PDF','JPG','JPEG','PNG','WEBP'] as $e) { 
      @unlink($uploadsFs . "/{$student_id}_N.$e"); 
    }

    $destFs = $uploadsFs . "/{$student_id}_N.$ext";
    
    if (@move_uploaded_file($nf['tmp_name'], $destFs)) {
      @chmod($destFs,0644);
      error_log("[UPLOAD] National ID saved: $destFs");
    } else {
      error_log("[UPLOAD] move failed (national) to $destFs");
    }
  }
}

/* --- Medical Report -> uploads/<id>_M.<ext> --- */
if (!empty($_FILES['file_medical_report']['name']) && $_FILES['file_medical_report']['error'] === UPLOAD_ERR_OK) {
  $mf  = $_FILES['file_medical_report'];
  $ext = strtolower(pathinfo($mf['name'], PATHINFO_EXTENSION));
  if (in_array($ext, ['pdf','jpg','jpeg','png','webp'], true) && $mf['size'] <= $MAX && is_uploaded_file($mf['tmp_name'])) {

    // clean old variants (case-insensitive)
    foreach (['pdf','jpg','jpeg','png','webp','PDF','JPG','JPEG','PNG','WEBP'] as $e) { 
      @unlink($uploadsFs . "/{$student_id}_M.$e"); 
    }

    $destFs = $uploadsFs . "/{$student_id}_M.$ext";
    
    if (@move_uploaded_file($mf['tmp_name'], $destFs)) {
      @chmod($destFs,0644);
      error_log("[UPLOAD] Medical report saved: $destFs");
    } else {
      error_log("[UPLOAD] move failed (medical) to $destFs");
    }
  }
}

/* --- Discount Justification -> uploads/<id>_D.<ext> --- */
if (!empty($_FILES['file_discount_justification']['name']) && $_FILES['file_discount_justification']['error'] === UPLOAD_ERR_OK) {
  $df  = $_FILES['file_discount_justification'];
  $ext = strtolower(pathinfo($df['name'], PATHINFO_EXTENSION));
  if (in_array($ext, ['pdf','jpg','jpeg','png','webp'], true) && $df['size'] <= $MAX && is_uploaded_file($df['tmp_name'])) {

    // clean old variants (case-insensitive)
    foreach (['pdf','jpg','jpeg','png','webp','PDF','JPG','JPEG','PNG','WEBP'] as $e) { 
      @unlink($uploadsFs . "/{$student_id}_D.$e"); 
    }

    $destFs = $uploadsFs . "/{$student_id}_D.$ext";
    
    if (@move_uploaded_file($df['tmp_name'], $destFs)) {
      @chmod($destFs,0644);
      error_log("[UPLOAD] Discount justification saved: $destFs");
    } else {
      error_log("[UPLOAD] move failed (discount) to $destFs");
    }
  }
}

/* ===================== EMAIL CONFIRMATION ===================== */
$email_sent = false;
$notification_results = [];

try {
    // Get student data for email
    $student_data = $mysqli1->prepare("SELECT student_name, student_name_eng, email FROM students WHERE student_id = ?");
    $student_data->bind_param("s", $student_id);
    $student_data->execute();
    $student = $student_data->get_result()->fetch_assoc();
    $student_data->close();

    if ($student && !empty($student['email'])) {
        $student_name = $student['student_name'] ?? $student['student_name_eng'] ?? 'الطالب';
        $toEmail = $student['email'];

        $email_subject = "تم تحديث ملفك الشخصي بنجاح - Profile Updated Successfully";
        
        $email_body = "
        <html>
        <body style='font-family: Cairo, Arial, sans-serif; direction: rtl;'>
            <div style='max-width: 600px; margin: 0 auto; padding: 20px; background: #f8fafc;'>
                <div style='background: linear-gradient(135deg, #1F3A2E, #3E6B54); color: white; padding: 20px; border-radius: 10px; text-align: center;'>
                    <h1>تم تحديث الملف الشخصي</h1>
                    <p>Profile Updated Successfully</p>
                </div>
                <div style='background: white; padding: 20px; border-radius: 0 0 10px 10px;'>
                    <p>عزيزي/عزيزتي <strong>{$student_name}</strong>,</p>
                    <p>تم تحديث ملفك الشخصي بنجاح في نظام القبول الإلكتروني.</p>
                    <p><strong>رقم الطالب:</strong> {$student_id}</p>
                    <p>سيتم مراجعة طلبك من قبل لجنة القبول وسيتم إبلاغك بالنتيجة في أقرب وقت.</p>
                    <br>
                    <p>Dear <strong>{$student_name}</strong>,</p>
                    <p>Your profile has been successfully updated in the electronic admission system.</p>
                    <p><strong>Student ID:</strong> {$student_id}</p>
                    <p>Your application will be reviewed by the admission committee and you will be notified of the result soon.</p>
                    <br>
                    <p>مع أطيب التمنيات,</p>
                    <p>Best regards,</p>
                    <p><strong>لجنة القبول - Admission Committee</strong><br>الجامعة الوطنية - National University - Sudan</p>
                </div>
            </div>
        </body>
        </html>
        ";

        /* ===================== SEND EMAIL ===================== */
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers .= "From: الجامعة الوطنية <no-reply@nu.edu.sd>\r\n";
        $headers .= "Reply-To: no-reply@nu.edu.sd\r\n";
        
        $encoded_subject = '=?UTF-8?B?' . base64_encode($email_subject) . '?=';
        
        $email_sent = mail($toEmail, $encoded_subject, $email_body, $headers);
        
        if ($email_sent) {
            $notification_results[] = "تم إرسال تأكيد بالبريد الإلكتروني";
            error_log("[EMAIL] Confirmation sent to: {$toEmail}");
        } else {
            $notification_results[] = "لم يتم إرسال البريد الإلكتروني";
            error_log("[EMAIL] Failed to send to: {$toEmail}");
        }
    } else {
        $notification_results[] = "لا يوجد بريد إلكتروني مسجل";
        error_log("[EMAIL] No email address found for student: {$student_id}");
    }
} catch (Exception $e) {
    error_log("[EMAIL] Error: " . $e->getMessage());
    $notification_results[] = "تعذر إرسال البريد الإلكتروني";
}

/* ---------- Send SMS notification ---------- */
try {
    // Get student name for SMS
    $student_name = null;
    if ($fetch = $mysqli1->prepare("SELECT student_name FROM students WHERE student_id = ?")) {
        $fetch->bind_param("s", $student_id);
        if ($fetch->execute()) {
            $fetch->bind_result($student_name);
            $fetch->fetch();
        }
        $fetch->close();
    }

    $display_name = $student_name ?: ($data['student_name_eng'] ?: 'الطالب');
    
    // Send SMS if phone number exists
    if (!empty($data['phone_number']) && function_exists('brq_send_sms')) {
        $message = "عزيزي/عزيزتي {$display_name}، تم تحديث ملفك الشخصي بنجاح. سنقوم بمراجعته وإبلاغك بالنتيجة.";
        $toPhone = preg_replace('/\D/', '', $data['phone_number']);
        
        // Convert to international format for Sudan
        if (preg_match('/^0?9\d{8}$/', $toPhone)) {
    $toPhone = '249' . ltrim($toPhone, '0');
}

if (preg_match('/^249\d{9}$/', $toPhone)) {
    $sms = brq_send_sms($toPhone, $message, 'UOFG', ['unicode' => true]);
    if ($sms['ok']) {
        $notification_results[] = "تم إرسال رسالة نصية";
        error_log("[SMS] Notification sent to {$toPhone}");
    } else {
        $notification_results[] = "لم يتم إرسال الرسالة النصية";
        error_log("[SMS] Send failed: " . ($sms['error'] ?? 'Unknown error'));
    }
}
    }
} catch (Exception $e) {
    // Don't let SMS failure break the submission
    error_log("[SMS] Exception: " . $e->getMessage());
    $notification_results[] = "تعذر إرسال الرسالة النصية";
}

/* ---------- Store notification results in session for success page ---------- */
if (!empty($notification_results)) {
    session_start();
    $_SESSION['update_notifications'] = implode(' - ', $notification_results);
}

/* ---------- Redirect to success page ---------- */
header("Location: student_success.php");
exit;