<?php
// interview_decide.php - Fixed version with correct database connection
ob_start();
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

require 'db.php';
require 'helpers.php';
require_committee();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !verify_csrf($_POST['csrf'] ?? '')) {
  http_response_code(400);
  echo 'Bad request';
  exit;
}

$pk         = (int)($_POST['pk'] ?? 0);
$student_id = trim($_POST['student_id'] ?? '');
$decision   = $_POST['decision'] ?? '';
$comment    = trim($_POST['comment'] ?? '');

// Debug the incoming data
error_log("Incoming data - PK: $pk, Student ID: $student_id, Decision: $decision");

if ($pk <= 0 || $student_id === '' || !in_array($decision, ['accepted','rejected'], true)) {
  http_response_code(400);
  echo 'ملف الطالب غير مكتمل - البيانات الاساسية و الملف الطبي';
  exit;
}

// Use the same database connection as interview_review.php
$host = 'localhost';
$username = 'uofsedu_Rmn';
$password = 'Almnsi@27';
$database = 'uofsedu_UT3';

try {
    $mysqli = new mysqli($host, $username, $password, $database);
    $mysqli->set_charset('utf8mb4');
    
    if ($mysqli->connect_error) {
        throw new Exception("Connection failed: " . $mysqli->connect_error);
    }
} catch (Exception $e) {
    die("Database connection error: " . $e->getMessage());
}

// Ensure columns exist
$mysqli->query("ALTER TABLE students 
    ADD COLUMN IF NOT EXISTS decision_status ENUM('pending','accepted','rejected') NOT NULL DEFAULT 'pending',
    ADD COLUMN IF NOT EXISTS interview_status ENUM('pending','accepted','rejected') NOT NULL DEFAULT 'pending',
    ADD COLUMN IF NOT EXISTS committee_comment TEXT NULL");

// FIXED: Check for 'rejected' not 'reject'
if ($decision === 'rejected' && mb_strlen($comment) < 5) {
  ob_end_clean();
  header("Location: interview_review.php?student_id=" . urlencode($student_id) . "&err=" . urlencode("يجب كتابة سبب الرفض (5 أحرف على الأقل)."));
  exit;
}

// FIXED: Simplified status mapping since form already sends 'accepted'/'rejected'
$status = $decision; // Decision is already 'accepted' or 'rejected'

// Debug: Log the status values
error_log("Final Status: $status, PK: $pk, Student ID: $student_id");

// Check if 'excluded' column exists before using it
$excluded_used = false;
$result = $mysqli->query("SHOW COLUMNS FROM students LIKE 'excluded'");
if ($result && $result->num_rows > 0) {
    $excluded_used = true;
}

// Update both decision_status and interview_status
 if ($excluded_used) {
    // FIXED: Use $status to determine excluded
    $excluded = ($status === 'rejected') ? 1 : 0;
    $stmt = $mysqli->prepare("UPDATE students SET excluded=?, decision_status=?, interview_status=?, committee_comment=? WHERE student_id=?");
    if ($stmt) {
        $stmt->bind_param("issss", $excluded, $status, $status, $comment, $student_id);
    }
} else {
    $stmt = $mysqli->prepare("UPDATE students SET decision_status=?, interview_status=?, committee_comment=? WHERE student_id=?");
    if ($stmt) {
        $stmt->bind_param("ssss", $status, $status, $comment, $student_id);
    }
}

if (!$stmt) {
  error_log('DECIDE prepare failed: '.$mysqli->error);
  ob_end_clean();
  header("Location: interview_review.php?student_id=" . urlencode($student_id) . "&err=" . urlencode("تعذر حفظ القرار."));
  exit;
}

if (!$stmt->execute()) {
  error_log('DECIDE update failed: '.$stmt->error);
  ob_end_clean();
  header("Location: interview_review.php?student_id=" . urlencode($student_id) . "&err=" . urlencode("تعذر حفظ القرار."));
  exit;
}

$affected_rows = $stmt->affected_rows;
$stmt->close();

error_log("Update affected rows: $affected_rows");

// Verify the update was successful
 $verify_stmt = $mysqli->prepare("SELECT decision_status, interview_status FROM students WHERE student_id = ?");
$verify_stmt->bind_param("s", $student_id);
$verify_stmt->execute();
$verify_stmt->bind_result($db_decision_status, $db_interview_status);
$verify_stmt->fetch();
$verify_stmt->close();

error_log("After update - Decision Status: $db_decision_status, Interview Status: $db_interview_status");

// Safely create audit table
try {
    $mysqli->query("
    CREATE TABLE IF NOT EXISTS interview_decisions (
      id INT AUTO_INCREMENT PRIMARY KEY,
      student_id VARCHAR(64) NOT NULL,
      reviewer_id INT NULL,
      reviewer_name VARCHAR(255) NULL,
      decision ENUM('accepted','rejected') NOT NULL,
      comment TEXT NULL,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {
    // Ignore table creation errors
}

// Safely log the decision
try {
    $reviewer_id   = (int)($_SESSION['committee_id'] ?? $_SESSION['user_id'] ?? 0);
    $reviewer_name = (string)($_SESSION['committee_name'] ?? $_SESSION['username'] ?? '');
    $ins = $mysqli->prepare("INSERT INTO interview_decisions (student_id, reviewer_id, reviewer_name, decision, comment) VALUES (?,?,?,?,?)");
    if ($ins) { 
        $ins->bind_param("sisss", $student_id, $reviewer_id, $reviewer_name, $decision, $comment); 
        $ins->execute(); 
        $ins->close(); 
    }
} catch (Exception $e) {
    // Ignore audit log errors
}

/* ===================== NOTIFICATIONS ===================== */
$notification_results = [];

try {
    // Get student data for notifications
    $student_data = $mysqli->prepare("SELECT student_name, student_name_eng, email, phone_number, phone_number2, guardian_phone_number, program_fees, registration_fees, insurance_fees, discount 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) {
        $student_name = $student['student_name'] ?? $student['student_name_eng'] ?? 'الطالب';
        $toEmail = $student['email'] ?? '';
        
        // Collect only the primary phone number
        $phoneNumbers = [];
        $primaryPhone = $student['phone_number'] ?? '';
        if (!empty($primaryPhone)) {
            $phoneNumbers[] = $primaryPhone;
        }
        
        // Calculate total fees after discount
        $program_fees = $student['program_fees'] ?? 0;
        $registration_fees = $student['registration_fees'] ?? 0;
        $insurance_fees = $student['insurance_fees'] ?? 0;
        $discount = $student['discount'] ?? 0;

        // Calculate total fees
        $total_fees = $program_fees + $registration_fees + $insurance_fees;

        // Apply discount if any
        if ($discount > 0) {
            $discount_amount = ($total_fees * $discount) / 100;
            $total_fees_after_discount = $total_fees - $discount_amount;
        } else {
            $total_fees_after_discount = $total_fees;
        }

        // Format the amount for display
        $formatted_total = number_format($total_fees_after_discount, 2) . ' SDG';

        // FIXED: Use $decision which is already 'accepted' or 'rejected'
        if ($decision === 'accepted') {
            $email_subject = "تهانينا! تم قبول طلبك في جامعة الجزيرة";
            $sms_text = "عزيزي/عزيزتي {$student_name}، تم قبول طلبك في جامعة الجزيرة. إجمالي الرسوم : {$formatted_total}.";
            $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>تم قبول طلب الالتحاق بجامعة الجزيرة</p>
                    </div>
                    <div style='background: white; padding: 20px; border-radius: 0 0 10px 10px;'>
                        <p>عزيزي/عزيزتي <strong>{$student_name}</strong>,</p>
                        <p>يسرنا إبلاغك <strong>بقبول طلب الالتحاق</strong> بجامعة الجزيرة.</p>
                        
                        <div style='background: #f0f9ff; padding: 15px; border-radius: 8px; margin: 15px 0; border-right: 4px solid #0ea5e9;'>
                            <h6 style='color: #0369a1; margin-bottom: 10px;'><i class='fas fa-money-bill-wave'></i> الرسوم الدراسية</h6>
                            <table style='width: 100%; border-collapse: collapse;'>
                                <tr>
                                    <td style='padding: 5px 0; color: #6b7280;'>رسوم البرنامج:</td>
                                    <td style='padding: 5px 0; text-align: left;'>" . number_format($program_fees, 2) . " SDG</td>
                                </tr>
                                <tr>
                                    <td style='padding: 5px 0; color: #6b7280;'>رسوم التسجيل:</td>
                                    <td style='padding: 5px 0; text-align: left;'>" . number_format($registration_fees, 2) . " SDG</td>
                                </tr>
                                <tr>
                                    <td style='padding: 5px 0; color: #6b7280;'>رسوم التأمين والكشف الطبي والخدمات:</td>
                                    <td style='padding: 5px 0; text-align: left;'>" . number_format($insurance_fees, 2) . " SDG</td>
                                </tr>";
            
            if ($discount > 0) {
                $email_body .= "
                                <tr>
                                    <td style='padding: 5px 0; color: #6b7280;'>الخصم ({$discount}%):</td>
                                    <td style='padding: 5px 0; text-align: left; color: #10b981;'>-" . number_format($discount_amount, 2) . " SDG</td>
                                </tr>";
            }
            
            $email_body .= "
                                <tr style='border-top: 1px solid #e5e7eb;'>
                                    <td style='padding: 8px 0; font-weight: bold; color: #1f2937;'>الإجمالي:</td>
                                    <td style='padding: 8px 0; text-align: left; font-weight: bold; color: #1f2937;'>{$formatted_total}</td>
                                </tr>
                            </table>
                        </div>
                        
                        <p>يرجى مراجعة حسابك في البوابة الإلكترونية لمزيد من التفاصيل حول إجراءات التسجيل وسداد الرسوم.</p>
                        <br>
                        <p>مع أطيب التمنيات,</p>
                        <p><strong>لجنة القبول</strong><br>جامعة الجزيرة</p>
                    </div>
                </div>
            </body>
            </html>
            ";
        } else {
            $email_subject = "تحديث حول طلب الالتحاق بجامعة الجزيرة";
            $reason = $comment ?: 'نعتذر عن قبول طلبك في هذه المرحلة.';
            
            // Include the reason in SMS for rejected cases
            if (!empty($comment)) {
                $sms_text = "عزيزي/عزيزتي {$student_name}، نأسف لإبلاغك بعدم قبول طلبك في جامعة الجزيرة. سبب الرفض: {$comment}";
            } else {
                $sms_text = "عزيزي/عزيزتي {$student_name}، نأسف لإبلاغك بعدم قبول طلبك في جامعة الجزيرة. نشكرك على اهتمامك.";
            }
            
            $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: #f59e0b; color: white; padding: 20px; border-radius: 10px; text-align: center;'>
                        <h1>تحديث حول طلب الالتحاق</h1>
                    </div>
                    <div style='background: white; padding: 20px; border-radius: 0 0 10px 10px;'>
                        <p>عزيزي/عزيزتي <strong>{$student_name}</strong>,</p>
                        <p>نأسف لإبلاغك بعدم قبول طلب الالتحاق بجامعة الجزيرة في هذه المرحلة.</p>
                        " . (!empty($comment) ? "<p><strong>سبب الرفض:</strong> {$comment}</p>" : "") . "
                        <p>نشكرك على اهتمامك بالانضمام إلى جامعتنا ونتمنى لك التوفيق في مساعيك الأكاديمية المستقبلية.</p>
                        <br>
                        <p>مع أطيب التمنيات,</p>
                        <p><strong>لجنة القبول</strong><br>جامعة الجزيرة</p>
                    </div>
                </div>
            </body>
            </html>
            ";
        }

        /* ===================== EMAIL NOTIFICATION ===================== */
        $email_sent = false;
        if ($toEmail && filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            $headers .= "From: جامعة الجزيرة <admissions@uofg.edu.sd>\r\n";
            $headers .= "Reply-To: admissions@uofg.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[] = "تم إرسال البريد الإلكتروني";
            } else {
                $notification_results[] = "لم يتم إرسال البريد الإلكتروني";
            }
        } else {
            $notification_results[] = "لا يوجد بريد إلكتروني صالح";
        }

        /* ===================== SMS NOTIFICATION ===================== */
        $sms_sent_count = 0;
        if (!empty($phoneNumbers)) {
            foreach ($phoneNumbers as $toPhone) {
                if (!empty($toPhone)) {
                    // Clean and validate phone number
                    $clean_phone = preg_replace('/\D/', '', $toPhone);
                    
                    // Convert to international format for Sudan
                    if (preg_match('/^0?9\d{8}$/', $clean_phone)) {
                        $clean_phone = '249' . ltrim($clean_phone, '0');
                    }
                    
                    // FIXED: Must start with 249 and have exactly 9 more digits
                    if (preg_match('/^249\d{9}$/', $clean_phone)) {
                        // Use your working SMS function
                        if (function_exists('brq_send_sms')) {
                            $sms_result = brq_send_sms($clean_phone, $sms_text, 'UOFG', ['unicode' => true]);
                            if ($sms_result['ok']) {
                                $sms_sent_count++;
                            }
                        } else {
                            // Fallback to basic SMS logging
                            error_log("SMS to {$clean_phone}: {$sms_text}");
                            $sms_sent_count++;
                        }
                    }
                }
            }
            
            if ($sms_sent_count > 0) {
                $notification_results[] = "تم إرسال {$sms_sent_count} رسالة نصية";
            } else {
                $notification_results[] = "لم يتم إرسال أي رسالة نصية";
            }
        } else {
            $notification_results[] = "لا توجد أرقام هواتف مسجلة";
        }
    }
} catch (Exception $e) {
    // If notifications fail, don't break the main functionality
    error_log("Notification error: " . $e->getMessage());
    $notification_results[] = "تعذر إرسال بعض الإشعارات";
}

/* ===================== FINAL REDIRECT ===================== */
ob_end_clean();

// Build final message in Arabic
if ($decision === 'accepted') {
    $base_message = "تم قبول الطلب بنجاح";
} else {
    $base_message = "تم رفض الطلب بنجاح";
}

// Add notification results to message
if (!empty($notification_results)) {
    $notification_summary = implode(' - ', $notification_results);
    $message = $base_message . " - " . $notification_summary;
} else {
    $message = $base_message;
}

// Use session for success message to display on the review page
$_SESSION['decision_main_message'] = $message;
$_SESSION['decision_success'] = true;

header("Location: committee_dashboard.php");
exit;
?>