<?php
// 🚀 بدء الجلسة يجب أن يكون أول أمر في الملف لكي لا تضيع الصلاحيات
if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once __DIR__ . '/security_headers.php';
require_once 'db_connect.php';

ob_clean();
header('Content-Type: application/json; charset=utf-8');

error_reporting(0);
ini_set('display_errors', 0);

try {
    // التحقق من الجلسة بشكل عام بدلاً من التقييد الصارم بأسماء الأدوار
    if (empty($_SESSION['loggedin'])) {
        echo json_encode(['status' => 'error', 'message' => 'غير مصرح لك. يرجى تسجيل الخروج والدخول مجدداً.']);
        exit;
    }

    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $current_school = isset($_SESSION['school_name']) ? $conn->real_escape_string($_SESSION['school_name']) : '';
    $operator = isset($_SESSION['display_name']) ? $conn->real_escape_string($_SESSION['display_name']) : (isset($_SESSION['manager_name']) ? $conn->real_escape_string($_SESSION['manager_name']) : 'محاسب الإدارة');

    // ====================================================
    // 1. إضافة قسم مالي
    if ($action === 'add_category') {
        $cat_name = $conn->real_escape_string(trim($_POST['category_name']));
        $cat_type = $conn->real_escape_string($_POST['category_type']);
        if (empty($cat_name)) { echo json_encode(['status' => 'error', 'message' => 'اسم القسم مطلوب.']); exit; }
        
        $check = $conn->query("SELECT category_id FROM acc_financial_categories WHERE school_name = '$current_school' AND category_name = '$cat_name'");
        if($check && $check->num_rows > 0) { echo json_encode(['status' => 'error', 'message' => 'هذا القسم موجود مسبقاً!']); exit; }

        $query = "INSERT INTO acc_financial_categories (school_name, category_name, category_type, is_system_default) 
                  VALUES ('$current_school', '$cat_name', '$cat_type', 0)";
        if ($conn->query($query)) echo json_encode(['status' => 'success', 'message' => 'تم إنشاء القسم المالي بنجاح.']);
        else echo json_encode(['status' => 'error', 'message' => 'فشل الحفظ: ' . $conn->error]);
        exit;
    }

    // ====================================================
    // 2. تحديث وحذف قسم مالي
    elseif ($action === 'update_category') {
        $cat_id = intval($_POST['category_id']);
        $cat_name = $conn->real_escape_string(trim($_POST['category_name']));
        $cat_type = $conn->real_escape_string($_POST['category_type']);
        
        $query = "UPDATE acc_financial_categories SET category_name = '$cat_name', category_type = '$cat_type' 
                  WHERE category_id = $cat_id AND is_system_default = 0 AND school_name = '$current_school'";
        if ($conn->query($query)) echo json_encode(['status' => 'success', 'message' => 'تم التعديل بنجاح.']);
        else echo json_encode(['status' => 'error', 'message' => 'فشل التعديل.']);
        exit;
    }

    elseif ($action === 'delete_category') {
        $cat_id = intval($_POST['category_id']);
        $query = "DELETE FROM acc_financial_categories WHERE category_id = $cat_id AND is_system_default = 0 AND school_name = '$current_school'";
        if ($conn->query($query)) echo json_encode(['status' => 'success', 'message' => 'تم حذف القسم المالي بنجاح.']);
        else echo json_encode(['status' => 'error', 'message' => 'فشل الحذف.']);
        exit;
    }

    // ====================================================
    // 3. حفظ مصفوفة الأسعار
    elseif ($action === 'save_pricing_matrix') {
        $conn->query("CREATE TABLE IF NOT EXISTS `acc_pricing_matrix` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `school_name` varchar(150) NOT NULL,
          `stage_name` varchar(100) NOT NULL,
          `base_price` decimal(15,2) NOT NULL DEFAULT '0.00',
          `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`),
          UNIQUE KEY `unique_stage_school` (`school_name`,`stage_name`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

        $pricing_data_json = $_POST['pricing_data'] ?? '{}';
        $pricing_data = json_decode($pricing_data_json, true);
        
        if (empty($pricing_data)) { echo json_encode(['status' => 'error', 'message' => 'لا توجد بيانات لحفظها.']); exit; }

        $success_count = 0;
        $stmt = $conn->prepare("INSERT INTO acc_pricing_matrix (school_name, stage_name, base_price) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE base_price = VALUES(base_price)");
        
        if ($stmt) {
            foreach ($pricing_data as $stage => $price) {
                $clean_stage = $conn->real_escape_string($stage);
                $clean_price = floatval($price);
                $stmt->bind_param("ssd", $current_school, $clean_stage, $clean_price);
                if ($stmt->execute()) $success_count++;
            }
            $stmt->close();
            if ($success_count > 0) echo json_encode(['status' => 'success', 'message' => 'تم حفظ التسعيرة بنجاح!']);
            else echo json_encode(['status' => 'error', 'message' => 'لم يتم حفظ أي بيانات.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'خطأ في قاعدة البيانات.']);
        }
        exit;
    }

    // ====================================================
    // 4. إعداد القيد المالي
    elseif ($action === 'setup_financials') {
        $student_id = $conn->real_escape_string(trim($_POST['student_id'] ?? ''));
        $total_amount = floatval($_POST['total_amount'] ?? 0);
        $discount = floatval($_POST['discount'] ?? 0);
        $payment_type = $conn->real_escape_string($_POST['payment_type'] ?? 'cash');

        if (empty($student_id)) {
            echo json_encode(['status' => 'error', 'message' => 'معرف الطالب مفقود.']);
            exit;
        }

        $check_fin = $conn->query("SELECT financial_id FROM acc_student_financials WHERE student_id = '$student_id'");
        $financial_id = 0;

        if ($check_fin && $check_fin->num_rows > 0) {
            $financial_id = $check_fin->fetch_assoc()['financial_id'];
            $conn->query("UPDATE acc_student_financials SET net_total = '$total_amount', discount_amount = '$discount' WHERE financial_id = '$financial_id'");
        } else {
            $conn->query("INSERT INTO acc_student_financials (student_id, plan_id, discount_percentage, discount_amount, net_total, total_paid, total_refunded, status) 
                          VALUES ('$student_id', 0, 0, '$discount', '$total_amount', 0, 0, 'active')");
            $financial_id = $conn->insert_id;
        }

        if ($payment_type === 'installments' && isset($_POST['inst_amount']) && isset($_POST['inst_date'])) {
            $conn->query("DELETE FROM acc_installments WHERE financial_id = '$financial_id' AND is_paid = 0");

            $inst_amounts = $_POST['inst_amount'];
            $inst_dates = $_POST['inst_date'];
            
            $stmt = $conn->prepare("INSERT INTO acc_installments (financial_id, student_id, due_date, amount_due, is_paid) VALUES (?, ?, ?, ?, 0)");
            for ($i = 0; $i < count($inst_amounts); $i++) {
                $due_date = $conn->real_escape_string($inst_dates[$i]);
                $amt_due = floatval($inst_amounts[$i]);
                $stmt->bind_param("issd", $financial_id, $student_id, $due_date, $amt_due);
                $stmt->execute();
            }
            $stmt->close();
        }
        echo json_encode(['status' => 'success', 'message' => 'تم إنشاء القيد المالي بنجاح!']);
        exit;
    }

    // ====================================================
    // 5. استلام دفعة (تسديد)
    elseif ($action === 'pay') {
        $student_id = $conn->real_escape_string($_POST['student_id'] ?? '');
        $amount = floatval($_POST['amount'] ?? 0);
        $date = $conn->real_escape_string($_POST['date'] ?? date('Y-m-d'));
        $method = $conn->real_escape_string($_POST['method'] ?? 'كاش');

        if (empty($student_id) || $amount <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات الدفعة غير صحيحة.']); exit;
        }

        // 1. Get financial_id
        $fin_res = $conn->query("SELECT financial_id FROM acc_student_financials WHERE student_id = '$student_id' LIMIT 1");
        if (!$fin_res || $fin_res->num_rows === 0) {
            echo json_encode(['status' => 'error', 'message' => 'الطالب ليس لديه قيد مالي.']); exit;
        }
        $financial_id = $fin_res->fetch_assoc()['financial_id'];

        // 2. Insert Payment
        $stmt = $conn->prepare("INSERT INTO acc_payments (financial_id, amount_paid, payment_method, payment_date, received_by) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sdsss", $financial_id, $amount, $method, $date, $operator);
        if(!$stmt->execute()) {
            echo json_encode(['status' => 'error', 'message' => 'فشل حفظ وصل السداد: ' . $stmt->error]); exit;
        }
        $stmt->close();

        // 3. Update total_paid based on actual sum
        $conn->query("UPDATE acc_student_financials f SET total_paid = (SELECT COALESCE(SUM(amount_paid), 0) FROM acc_payments p WHERE p.financial_id = f.financial_id) WHERE student_id = '$student_id'");

        // 4. Smart Installment Resolver
        $fin_res_new = $conn->query("SELECT total_paid FROM acc_student_financials WHERE student_id = '$student_id' LIMIT 1");
        $total_paid = floatval($fin_res_new->fetch_assoc()['total_paid']);

        $inst_res = $conn->query("SELECT installment_id, amount_due FROM acc_installments WHERE financial_id = '$financial_id' ORDER BY due_date ASC");
        if ($inst_res) {
            $cumulative = 0;
            while($inst = $inst_res->fetch_assoc()) {
                $inst_id = $inst['installment_id'];
                $cumulative += floatval($inst['amount_due']);
                $is_paid = ($total_paid >= ($cumulative - 0.1)) ? 1 : 0; 
                $conn->query("UPDATE acc_installments SET is_paid = $is_paid WHERE installment_id = '$inst_id'");
            }
        }

        echo json_encode(['status' => 'success', 'message' => 'تم استلام الدفعة وتسوية الأقساط بنجاح!']);
        exit;
    }

    // ====================================================
    // 5.1 🚀 استرجاع مبلغ للطالب المنسحب/المؤقت (العملية الجديدة) 🚀
    elseif ($action === 'refund_student') {
        $student_id = $conn->real_escape_string($_POST['student_id'] ?? '');
        $amount = floatval($_POST['amount'] ?? 0);
        $date = $conn->real_escape_string($_POST['date'] ?? date('Y-m-d'));
        $student_name = $conn->real_escape_string($_POST['student_name'] ?? 'طالب');
        $desc = "سند صرف استرجاع فائض مالي للطالب المنسحب/المؤقت: " . $student_name;

        if (empty($student_id) || $amount <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات السند غير صحيحة.']); exit;
        }

        // 1. تحديث حساب الطالب بإضافة المبلغ للعمود المسترجع
        $conn->query("UPDATE acc_student_financials SET total_refunded = total_refunded + $amount WHERE student_id = '$student_id'");

        // 2. تسجيلها في الصرفيات لتنزل من خزينة المدرسة
        $stmt = $conn->prepare("INSERT INTO acc_expenses (category_name, amount, expense_date, description, recorded_by) VALUES ('تصفية مسترجعات طلاب', ?, ?, ?, ?)");
        $stmt->bind_param("dsss", $amount, $date, $desc, $operator);
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'تم صرف المسترجعات للطالب وتصفية حسابه بنجاح!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'فشل إصدار سند الصرف: ' . $stmt->error]);
        }
        $stmt->close();
        exit;
    }

    // ====================================================
    // 6. الجدولة
    elseif ($action === 'reschedule') {
        $student_id = $conn->real_escape_string(trim($_POST['student_id'] ?? ''));
        if (empty($student_id) || !isset($_POST['resch_amount']) || !isset($_POST['resch_date'])) {
            echo json_encode(['status' => 'error', 'message' => 'بيانات الجدولة ناقصة.']);
            exit;
        }

        $check_fin = $conn->query("SELECT financial_id FROM acc_student_financials WHERE student_id = '$student_id'");
        if ($check_fin && $check_fin->num_rows > 0) {
            $financial_id = $check_fin->fetch_assoc()['financial_id'];
            
            $conn->query("DELETE FROM acc_installments WHERE financial_id = '$financial_id' AND is_paid = 0");

            $amounts = $_POST['resch_amount'];
            $dates = $_POST['resch_date'];
            
            $stmt = $conn->prepare("INSERT INTO acc_installments (financial_id, student_id, due_date, amount_due, is_paid) VALUES (?, ?, ?, ?, 0)");
            for ($i = 0; $i < count($amounts); $i++) {
                $date = $conn->real_escape_string($dates[$i]);
                $amt = floatval($amounts[$i]);
                $stmt->bind_param("issd", $financial_id, $student_id, $date, $amt);
                $stmt->execute();
            }
            $stmt->close();
            echo json_encode(['status' => 'success', 'message' => 'تم اعتماد جدول الأقساط الجديد بنجاح.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'لا يوجد قيد مالي مسبق لهذا الطالب.']);
        }
        exit;
    }

    // ====================================================
    // 7. جلب بيانات كشف الحساب
    elseif ($action === 'get_statement') {
        $student_id = $conn->real_escape_string(trim($_POST['student_id'] ?? ''));
        if (empty($student_id)) { throw new Exception("معرف الطالب مفقود."); }

        $response_data = [
            'info' => [],
            'payments' => [],
            'installments' => []
        ];

        // 1. جلب المعلومات الأساسية (مع المسترجع)
        $info_query = $conn->query("
            SELECT s.student_id, s.student_name, s.stage, s.department, f.financial_id, f.net_total, f.total_paid, f.total_refunded 
            FROM students s 
            LEFT JOIN acc_student_financials f ON s.student_id = f.student_id 
            WHERE s.student_id = '$student_id' LIMIT 1
        ");
        
        if ($info_query && $info_query->num_rows > 0) {
            $row = $info_query->fetch_assoc();
            $response_data['info'] = [
                'id' => $row['student_id'],
                'name' => $row['student_name'],
                'stage' => $row['stage'],
                'dept' => $row['department'],
                'net_total' => $row['net_total'] ?? 0,
                'total_paid' => $row['total_paid'] ?? 0,
                'total_refunded' => $row['total_refunded'] ?? 0
            ];
            $fin_id = $row['financial_id'];

            if ($fin_id > 0) {
                // 2. جلب المدفوعات السابقة
                $pay_query = $conn->query("SELECT payment_id, amount_paid, payment_date, payment_method, received_by FROM acc_payments WHERE financial_id = '$fin_id' ORDER BY payment_date DESC");
                if ($pay_query && $pay_query->num_rows > 0) {
                    while($p = $pay_query->fetch_assoc()) {
                        $response_data['payments'][] = [
                            'id' => $p['payment_id'],
                            'amount' => $p['amount_paid'],
                            'date' => date('Y-m-d', strtotime($p['payment_date'])),
                            'method' => $p['payment_method'],
                            'accountant' => $p['received_by']
                        ];
                    }
                }

                // 3. جلب الأقساط المجدولة
                $inst_query = $conn->query("SELECT due_date, amount_due, is_paid FROM acc_installments WHERE financial_id = '$fin_id' ORDER BY due_date ASC");
                if ($inst_query && $inst_query->num_rows > 0) {
                    while($i = $inst_query->fetch_assoc()) {
                        $response_data['installments'][] = [
                            'date' => $i['due_date'],
                            'amount' => $i['amount_due'],
                            'is_paid' => $i['is_paid']
                        ];
                    }
                }
            }
            echo json_encode(['status' => 'success', 'data' => $response_data]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'الطالب غير موجود.']);
        }
        exit;
    }

    // ====================================================
    // 8. إرسال كشف الحساب للإيميل (لولي الأمر)
    elseif ($action === 'send_statement_email') {
        $student_id = $conn->real_escape_string(trim($_POST['student_id'] ?? ''));
        if (empty($student_id)) throw new Exception("معرف الطالب مفقود.");

        // جلب بيانات الطالب والإيميل
        $info_query = $conn->query("
            SELECT s.student_name, s.email, f.financial_id, f.net_total, f.total_paid, f.total_refunded 
            FROM students s 
            LEFT JOIN acc_student_financials f ON s.student_id = f.student_id 
            WHERE s.student_id = '$student_id' LIMIT 1
        ");

        if (!$info_query || $info_query->num_rows === 0) {
            echo json_encode(['status' => 'error', 'message' => 'الطالب غير موجود.']); exit;
        }

        $row = $info_query->fetch_assoc();
        $email = trim($row['email']);
        $student_name = $row['student_name'];
        $net_total = floatval($row['net_total'] ?? 0);
        $total_paid = floatval($row['total_paid'] ?? 0);
        $total_refunded = floatval($row['total_refunded'] ?? 0);
        
        $actual_paid = $total_paid - $total_refunded;
        $debt = max(0, $net_total - $actual_paid);
        $fin_id = $row['financial_id'];

        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(['status' => 'error', 'message' => 'لا يوجد بريد إلكتروني صالح مسجل في بطاقة هذا الطالب. يرجى إضافته أولاً.']);
            exit;
        }

        // جلب المدفوعات لتضمينها في الإيميل
        $payments_html = "";
        $pay_query = $conn->query("SELECT amount_paid, payment_date, payment_method FROM acc_payments WHERE financial_id = '$fin_id' ORDER BY payment_date DESC");
        if ($pay_query && $pay_query->num_rows > 0) {
            while($p = $pay_query->fetch_assoc()) {
                $amt = number_format($p['amount_paid']);
                $date = date('Y-m-d', strtotime($p['payment_date']));
                $payments_html .= "<tr>
                    <td style='padding:10px; border:1px solid #e2e8f0; text-align:center;'>{$date}</td>
                    <td style='padding:10px; border:1px solid #e2e8f0; text-align:center; color:#10b981; font-weight:bold;'>{$amt} د.ع</td>
                    <td style='padding:10px; border:1px solid #e2e8f0; text-align:center;'>{$p['payment_method']}</td>
                </tr>";
            }
        } else {
            $payments_html = "<tr><td colspan='3' style='padding:10px; border:1px solid #e2e8f0; text-align:center; color:#64748b;'>لا توجد مدفوعات مسجلة حتى الآن</td></tr>";
        }

        // بناء قالب الإيميل (HTML)
        $raw_subject = "كشف حساب مالي - " . $student_name;
        $subject = "=?UTF-8?B?" . base64_encode($raw_subject) . "?=";
        
        $message = "
        <html dir='rtl'>
        <body style='font-family: Tahoma, Arial, sans-serif; background-color: #f8fafc; padding: 20px;'>
            <div style='max-width: 600px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 12px; border-top: 5px solid #3b82f6; box-shadow: 0 4px 6px rgba(0,0,0,0.05);'>
                
                <h2 style='color: #1e293b; text-align: center; margin-bottom: 20px;'>كشف حساب مالي</h2>
                
                <div style='background-color: #f1f5f9; padding: 15px; border-radius: 8px; margin-bottom: 20px;'>
                    <p style='margin: 5px 0; font-size: 14px;'><strong>اسم الطالب:</strong> {$student_name}</p>
                    <p style='margin: 5px 0; font-size: 14px;'><strong>المعرف (الكود):</strong> {$student_id}</p>
                </div>

                <div style='display: flex; justify-content: space-between; margin-bottom: 20px;'>
                    <div style='width: 48%; background-color: #eff6ff; padding: 15px; border-radius: 8px; text-align: center;'>
                        <p style='margin: 0; font-size: 12px; color: #64748b;'>القسط السنوي</p>
                        <p style='margin: 5px 0 0; font-size: 18px; font-weight: bold; color: #3b82f6;'>" . number_format($net_total) . "</p>
                    </div>
                    <div style='width: 48%; background-color: #fef2f2; padding: 15px; border-radius: 8px; text-align: center;'>
                        <p style='margin: 0; font-size: 12px; color: #64748b;'>المتبقي (الديون)</p>
                        <p style='margin: 5px 0 0; font-size: 18px; font-weight: bold; color: #ef4444;'>" . number_format($debt) . "</p>
                    </div>
                </div>

                <h3 style='color: #10b981; border-bottom: 2px solid #10b981; padding-bottom: 8px; margin-top: 30px; font-size: 16px;'>سجل المدفوعات (الواصل)</h3>
                <table style='width: 100%; border-collapse: collapse; font-size: 13px;'>
                    <thead>
                        <tr style='background-color: #f8fafc;'>
                            <th style='padding:10px; border:1px solid #e2e8f0; color:#475569;'>التاريخ</th>
                            <th style='padding:10px; border:1px solid #e2e8f0; color:#475569;'>المبلغ المستلم</th>
                            <th style='padding:10px; border:1px solid #e2e8f0; color:#475569;'>طريقة الدفع</th>
                        </tr>
                    </thead>
                    <tbody>
                        {$payments_html}
                    </tbody>
                </table>
                
                <p style='text-align: center; color: #94a3b8; font-size: 11px; margin-top: 30px;'>
                    هذا البريد تم إصداره آلياً من النظام المالي الأكاديمي.<br>
                    تاريخ الإصدار: " . date('Y-m-d H:i') . "
                </p>
            </div>
        </body>
        </html>
        ";

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";
        $headers .= "From: Roozmari Academy <noreply@roozmari.com>\r\n";

        if (@mail($email, $subject, $message, $headers)) {
            echo json_encode(['status' => 'success', 'message' => 'تم إرسال كشف الحساب إلى إيميل الطالب بنجاح!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'فشل إرسال البريد. يرجى التأكد من إعدادات سيرفر الاستضافة.']);
        }
        exit;
    }

    else {
        echo json_encode(['status' => 'error', 'message' => 'إجراء غير معروف.']);
        exit;
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'خطأ نظام: ' . $e->getMessage()]);
    exit;
}