<?php
session_start();
require_once 'db_connect.php';
header('Content-Type: application/json; charset=utf-8');

// إيقاف عرض الأخطاء النصية لمنع تخريب استجابة الـ JSON
ini_set('display_errors', 0);
error_reporting(0);

if (!$conn) {
    echo json_encode(['status' => 'error', 'message' => 'لا يوجد اتصال بقاعدة البيانات.']);
    exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : 'enroll';

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

    if (empty($student_id) || $amount <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'يرجى تحديد الطالب وإدخال مبلغ صحيح.']);
        exit;
    }

    $fin_res = $conn->query("SELECT financial_id, net_total, total_paid FROM acc_student_financials WHERE student_id = '$student_id' LIMIT 1");
    
    if ($fin_res && $fin_res->num_rows > 0) {
        $fin_row = $fin_res->fetch_assoc();
        $financial_id = $fin_row['financial_id'];
        
        $insert_payment = "INSERT INTO acc_payments (financial_id, installment_id, amount_paid, payment_date, payment_method) 
                           VALUES ($financial_id, NULL, $amount, '$date', '$method')";
                           
        if ($conn->query($insert_payment)) {
            
            $new_paid = $fin_row['total_paid'] + $amount;
            $new_status = ($new_paid >= $fin_row['net_total']) ? 'completed' : 'active';
            $conn->query("UPDATE acc_student_financials SET total_paid = $new_paid, status = '$new_status' WHERE financial_id = $financial_id");

            $inst_res = $conn->query("SELECT installment_id, amount_due FROM acc_installments WHERE financial_id = $financial_id AND is_paid = 0 ORDER BY due_date ASC");
            $remaining_payment = $amount;
            
            if ($inst_res && $inst_res->num_rows > 0) {
                while ($inst = $inst_res->fetch_assoc()) {
                    if ($remaining_payment <= 0) break;
                    $inst_id = $inst['installment_id'];
                    $inst_amount = floatval($inst['amount_due']);
                    
                    if ($remaining_payment >= $inst_amount) {
                        $conn->query("UPDATE acc_installments SET is_paid = 1 WHERE installment_id = $inst_id");
                        $remaining_payment -= $inst_amount;
                    } else {
                        $new_due = $inst_amount - $remaining_payment;
                        $conn->query("UPDATE acc_installments SET amount_due = $new_due WHERE installment_id = $inst_id");
                        $remaining_payment = 0;
                    }
                }
            }
            echo json_encode(['status' => 'success', 'message' => 'تم استلام الدفعة بنجاح وتحديث الحسابات بدقة!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'خطأ أثناء الحفظ في جدول المدفوعات: ' . $conn->error]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'لم يتم العثور على حساب مالي مسبق لهذا الطالب. يرجى عمل تسجيل مالي له أولاً.']);
    }

} elseif ($action === 'pay_salary') {
    // =========================================================
    // 2. تسجيل وصرف رواتب الموظفين والمدرسين
    // =========================================================
    $emp_id = intval($_POST['employee_id']);
    $month = $conn->real_escape_string($_POST['payment_month']);
    $base = floatval($_POST['base_amount']);
    $bonus = floatval($_POST['bonuses']);
    $deduction = floatval($_POST['deductions']);
    $method = $conn->real_escape_string($_POST['payment_method']);
    
    if ($emp_id <= 0 || $base < 0 || empty($month)) {
        echo json_encode(['status' => 'error', 'message' => 'يرجى تعبئة الحقول الأساسية بشكل صحيح.']);
        exit;
    }
    
    $contract_id = 0;
    $c_res = $conn->query("SELECT contract_id FROM acc_employee_contracts WHERE reference_id = $emp_id LIMIT 1");
    
    if ($c_res && $c_res->num_rows > 0) {
        $contract_id = $c_res->fetch_assoc()['contract_id'];
        $conn->query("UPDATE acc_employee_contracts SET base_salary = $base WHERE contract_id = $contract_id");
    } else {
        $t_res = $conn->query("SELECT role, DATE(last_active) as reg_date FROM teachers WHERE id = $emp_id LIMIT 1");
        $emp_type = 'teacher'; 
        $start_dt = date('Y-m-d'); 
        
        if ($t_res && $t_res->num_rows > 0) {
            $t_row = $t_res->fetch_assoc();
            $role = $t_row['role'];
            if ($role === 'admin') $emp_type = 'admin';
            elseif ($role === 'accountant' || $role === 'إداري') $emp_type = 'accountant';
            elseif ($role === 'staff') $emp_type = 'staff';
            
            if (!empty($t_row['reg_date']) && $t_row['reg_date'] != '0000-00-00') {
                $start_dt = $t_row['reg_date'];
            }
        }
        
        $conn->query("INSERT INTO acc_employee_contracts (employee_type, reference_id, base_salary, start_date) VALUES ('$emp_type', $emp_id, $base, '$start_dt')");
        $contract_id = $conn->insert_id;
    }
    
    $net = ($base + $bonus) - $deduction;
    $dt = date('Y-m-d H:i:s');
    
    $query = "INSERT INTO acc_salary_payments (contract_id, payment_month, base_amount, bonuses, deductions, net_paid, payment_date, payment_method) 
              VALUES ($contract_id, '$month', $base, $bonus, $deduction, $net, '$dt', '$method')";
              
    if ($conn->query($query)) {
        echo json_encode(['status' => 'success', 'message' => 'تم صرف وتسجيل راتب الموظف بنجاح!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'خطأ أثناء حفظ الراتب في قاعدة البيانات: ' . $conn->error]);
    }

} elseif ($action === 'reschedule') {
    // =========================================================
    // 🚀 إعادة جدولة الأقساط المتبقية للطالب 🚀
    // =========================================================
    
    // تأمين المدخلات
    $student_id = isset($_POST['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;
    }

    // 1. البحث عن الحساب المالي المرتبط بهذا الطالب
    $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) {
        $financial_id = $fin_res->fetch_assoc()['financial_id'];
        
        // 2. حذف جميع الأقساط "غير المدفوعة" السابقة المرتبطة بهذا الحساب
        // (نحتفظ بالأقساط التي تم دفعها بالفعل)
        $conn->query("DELETE FROM acc_installments WHERE financial_id = $financial_id AND is_paid = 0");
        
        // 3. إدراج الأقساط الجديدة التي أرسلها المحاسب من الواجهة
        $amounts = $_POST['resch_amount'];
        $dates = $_POST['resch_date'];
        
        $success = true;
        
        // دورة لإدخال كل قسط جديد على حدة
        for ($i = 0; $i < count($amounts); $i++) {
            $amt = floatval($amounts[$i]);
            $dt = $conn->real_escape_string($dates[$i]);
            
            // التأكد من أن المبلغ أكبر من صفر والتاريخ موجود
            if ($amt > 0 && !empty($dt)) {
                $insert_query = "INSERT INTO acc_installments (financial_id, due_date, amount_due, is_paid) VALUES ($financial_id, '$dt', $amt, 0)";
                if (!$conn->query($insert_query)) {
                    $success = false;
                }
            }
        }
        
        if ($success) {
            echo json_encode(['status' => 'success', 'message' => 'تم تحديث تواريخ ومبالغ الأقساط المتبقية بنجاح.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'حدث خطأ أثناء حفظ بعض الأقساط الجديدة.']);
        }

    } else {
        echo json_encode(['status' => 'error', 'message' => 'لم يتم العثور على حساب مالي لهذا الطالب.']);
    }



} elseif ($action === 'delete_salary') {
    $sp_id = intval($_POST['sp_id']);
    if ($conn->query("DELETE FROM acc_salary_payments WHERE sp_id = $sp_id")) {
        echo json_encode(['status' => 'success', 'message' => 'تم حذف سجل الراتب بنجاح.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'فشل عملية الحذف.']);
    }

} elseif ($action === 'update_employee') {
    $emp_id = intval($_POST['emp_id']);
    $new_title = $conn->real_escape_string($_POST['emp_title']);
    $new_phone = $conn->real_escape_string($_POST['emp_phone']);
    $new_base = floatval($_POST['emp_base_salary']);

    if ($emp_id > 0) {
        // 1. تحديث جدول المدرسين الأساسي
        $conn->query("UPDATE teachers SET title = '$new_title', phone = '$new_phone', base_salary = $new_base WHERE id = $emp_id");
        
        // 2. التحقق من وجود عقد مالي
        $check_contract = $conn->query("SELECT contract_id FROM acc_employee_contracts WHERE reference_id = $emp_id LIMIT 1");
        
        if ($check_contract && $check_contract->num_rows > 0) {
            // العقد موجود -> قم بتحديث الراتب فقط
            $conn->query("UPDATE acc_employee_contracts SET base_salary = $new_base WHERE reference_id = $emp_id");
        } else {
            // العقد غير موجود -> قم بإنشاء عقد جديد فوراً
            $t_res = $conn->query("SELECT role FROM teachers WHERE id = $emp_id LIMIT 1");
            $emp_type = 'teacher';
            if ($t_res && $t_res->num_rows > 0) {
                $role = $t_res->fetch_assoc()['role'];
                if ($role === 'admin') $emp_type = 'admin';
                elseif ($role === 'accountant' || $role === 'إداري') $emp_type = 'accountant';
            }
            $start_dt = date('Y-m-d');
            $conn->query("INSERT INTO acc_employee_contracts (employee_type, reference_id, base_salary, start_date) VALUES ('$emp_type', $emp_id, $new_base, '$start_dt')");
        }
        
        echo json_encode(['status' => 'success', 'message' => 'تم تحديث بيانات الموظف وتوليد العقد بنجاح!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'معرف الموظف غير صحيح.']);
    }

} elseif ($action === 'delete_employee') {
    $emp_id = intval($_POST['emp_id']);
    if ($emp_id > 0) {
        $conn->query("UPDATE teachers SET account_status = 'suspended' WHERE id = $emp_id");
        echo json_encode(['status' => 'success', 'message' => 'تم إنهاء خدمة الموظف وإزالته من السجلات النشطة.']);
    }

} elseif ($action === 'add_expense') {
    // =========================================================
    // 🚀 3. إضافة سند صرف جديد مع رفع المرفقات 🚀
    // =========================================================
    $expense_date = $conn->real_escape_string($_POST['expense_date']);
    $amount = floatval($_POST['amount']);
    $category_name = $conn->real_escape_string($_POST['category_name']);
    $recorded_by = $conn->real_escape_string($_POST['recorded_by']);
    $description = $conn->real_escape_string($_POST['description']);
    
    // إنشاء الجدول إذا لم يكن موجوداً
    $conn->query("CREATE TABLE IF NOT EXISTS acc_expenses (
        expense_id INT AUTO_INCREMENT PRIMARY KEY,
        category_name VARCHAR(100) NOT NULL,
        amount DECIMAL(10, 2) NOT NULL,
        expense_date DATE NOT NULL,
        description TEXT,
        invoice_attachment VARCHAR(255) NULL,
        recorded_by VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    $attachment_path = 'NULL';
    if(isset($_FILES['invoice_attachment']) && $_FILES['invoice_attachment']['error'] == 0) {
        $upload_dir = 'uploads/expenses/';
        if(!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $file_name = time() . '_' . preg_replace("/[^a-zA-Z0-9.]/", "", basename($_FILES['invoice_attachment']['name']));
        $target_file = $upload_dir . $file_name;
        if(move_uploaded_file($_FILES['invoice_attachment']['tmp_name'], $target_file)) {
            $attachment_path = "'" . $target_file . "'";
        }
    }

    $query = "INSERT INTO acc_expenses (category_name, amount, expense_date, description, invoice_attachment, recorded_by) 
              VALUES ('$category_name', $amount, '$expense_date', '$description', $attachment_path, '$recorded_by')";
              
    if ($conn->query($query)) {
        echo json_encode(['status' => 'success', 'message' => 'تم إصدار سند الصرف بنجاح وتحديث الخزينة!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'حدث خطأ أثناء حفظ السند: ' . $conn->error]);
    }
    
} elseif ($action === 'change_status') {
    // =========================================================
    // 🚀 تغيير حالة قيد الطالب (مستمر، مؤقت، منسحب) 🚀
    // =========================================================
    $student_id = isset($_POST['student_id']) ? $conn->real_escape_string(trim($_POST['student_id'])) : '';
    $new_status = isset($_POST['new_status']) ? $conn->real_escape_string(trim($_POST['new_status'])) : 'active';

    if (empty($student_id) || !in_array($new_status, ['active', 'temporary', 'withdrawn'])) {
        echo json_encode(['status' => 'error', 'message' => 'بيانات غير صالحة.']);
        exit;
    }

    // تحديث الحالة في جدول الطلاب
    $update_query = "UPDATE students SET enrollment_status = '$new_status' WHERE student_id = '$student_id'";
    
    if ($conn->query($update_query)) {
        echo json_encode(['status' => 'success', 'message' => 'تم تغيير حالة الطالب بنجاح ونقله إلى السجل المناسب.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'فشل في تحديث حالة الطالب: ' . $conn->error]);
    }



} elseif ($action === 'update_expense') {
    // =========================================================
    // 🚀 4. تحديث سند الصرف (تعديل السند من النافذة) 🚀
    // =========================================================
    $expense_id = intval($_POST['expense_id']);
    $expense_date = $conn->real_escape_string($_POST['expense_date']);
    $amount = floatval($_POST['amount']);
    $category_name = $conn->real_escape_string($_POST['category_name']);
    $recorded_by = $conn->real_escape_string($_POST['recorded_by']);
    $description = $conn->real_escape_string($_POST['description']);

    if ($expense_id > 0) {
        $query = "UPDATE acc_expenses SET 
                    category_name = '$category_name', 
                    amount = $amount, 
                    expense_date = '$expense_date', 
                    description = '$description', 
                    recorded_by = '$recorded_by' 
                  WHERE expense_id = $expense_id";
                  
        if ($conn->query($query)) {
            echo json_encode(['status' => 'success', 'message' => 'تم حفظ التعديلات على السند بنجاح!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'حدث خطأ أثناء التعديل: ' . $conn->error]);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'معرف السند غير صالح.']);
    }

} elseif ($action === 'delete_expense') {
    // =========================================================
    // 🚀 5. حذف سند الصرف 🚀
    // =========================================================
    $expense_id = intval($_POST['expense_id']);
    if ($expense_id > 0) {
        $conn->query("DELETE FROM acc_expenses WHERE expense_id = $expense_id");
        echo json_encode(['status' => 'success', 'message' => 'تم حذف السند وإرجاع مبلغه إلى الخزينة بنجاح.']);
    }

} else {
    // =========================================================
    // التسجيل المالي الأولي وجدولة الأقساط (للطلاب)
    // =========================================================
    $student_id = isset($_POST['student_id']) ? $conn->real_escape_string(trim($_POST['student_id'])) : '';
    $total_amount = isset($_POST['total_amount']) ? floatval($_POST['total_amount']) : 0;
    $discount = isset($_POST['discount']) ? floatval($_POST['discount']) : 0;
    $payment_type = isset($_POST['payment_type']) ? $conn->real_escape_string($_POST['payment_type']) : 'cash';

    if (empty($student_id) || $total_amount <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'يرجى اختيار الطالب وتحديد القسط الكلي بشكل صحيح.']);
        exit;
    }

    $net_total = $total_amount - ($total_amount * ($discount / 100));
    $discount_amount = $total_amount - $net_total;
    
    $initial_paid = ($payment_type === 'cash') ? $net_total : 0;
    $status = ($payment_type === 'cash') ? 'completed' : 'active';

    $conn->query("DELETE FROM acc_student_financials WHERE student_id = '$student_id'");

    $query = "INSERT INTO acc_student_financials (student_id, plan_id, discount_percentage, discount_amount, net_total, total_paid, status)
              VALUES ('$student_id', 0, $discount, $discount_amount, $net_total, $initial_paid, '$status')";

    if ($conn->query($query)) {
        $financial_id = $conn->insert_id;

        if ($payment_type === 'installments' && isset($_POST['inst_amount']) && isset($_POST['inst_date'])) {
            $amounts = $_POST['inst_amount'];
            $dates = $_POST['inst_date'];

            for ($i = 0; $i < count($amounts); $i++) {
                $amt = floatval($amounts[$i]);
                $dt = $conn->real_escape_string($dates[$i]);
                if ($amt > 0 && !empty($dt)) {
                    $conn->query("INSERT INTO acc_installments (financial_id, due_date, amount_due, is_paid) VALUES ($financial_id, '$dt', $amt, 0)");
                }
            }
        } else {
            $dt = date('Y-m-d');
            $conn->query("INSERT INTO acc_payments (financial_id, installment_id, amount_paid, payment_date, payment_method) VALUES ($financial_id, NULL, $initial_paid, '$dt', 'كاش')");
            $conn->query("INSERT INTO acc_installments (financial_id, due_date, amount_due, is_paid) VALUES ($financial_id, '$dt', $net_total, 1)");
        }

        echo json_encode(['status' => 'success', 'message' => 'تم حفظ السجل المالي وجدولة الأقساط بدقة!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'فشل الحفظ في قاعدة البيانات: ' . $conn->error]);
    }
}
?>