<?php
// admin/transactions.php - مدیریت تراکنش‌ها با جستجوی Ajax

session_start();
require_once '../config/database.php';
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

$user = getCurrentUser();
if (!in_array($user['role_level'], [1,2,5])) {
    header('Location: dashboard.php');
    exit;
}

$pageTitle = 'مدیریت تراکنش‌ها';
$pageSubtitle = 'ثبت و مدیریت مبالغ واریزی به اساتید';

// ===== دریافت پارامترها =====
$selected_teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;
$selected_term_id = isset($_GET['term_id']) ? (int)$_GET['term_id'] : 0;

// ===== دریافت لیست ترم‌ها =====
$allTerms = getAllTerms();

// ===== دریافت تراکنش‌ها =====
$transactions = [];
$selectedTeacher = null;
$totalAmount = 0;
$termTotals = [];

if ($selected_teacher_id > 0) {
    $selectedTeacher = fetchOne("SELECT * FROM users WHERE id = ?", [$selected_teacher_id]);
    
    $sql = "SELECT t.*, u.name as teacher_name, u.family as teacher_family, tm.name as term_name, tm.code as term_code 
            FROM transactions t 
            LEFT JOIN users u ON t.teacher_id = u.id 
            LEFT JOIN terms tm ON t.term_id = tm.id 
            WHERE t.teacher_id = ?";
    $params = [$selected_teacher_id];
    
    if ($selected_term_id > 0) {
        $sql .= " AND t.term_id = ?";
        $params[] = $selected_term_id;
    }
    $sql .= " ORDER BY t.payment_date DESC";
    
    $transactions = fetchAll($sql, $params);
    
    foreach ($transactions as $tr) {
        $totalAmount += $tr['amount'];
        $termKey = $tr['term_id'] ?? 0;
        $termName = $tr['term_name'] ?? 'بدون ترم';
        if (!isset($termTotals[$termKey])) {
            $termTotals[$termKey] = ['name' => $termName, 'total' => 0, 'count' => 0];
        }
        $termTotals[$termKey]['total'] += $tr['amount'];
        $termTotals[$termKey]['count']++;
    }
}

// ===== پردازش فرم =====
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add') {
        $teacherId = $_POST['teacher_id'] ?? 0;
        $amount = $_POST['amount'] ?? 0;
        $payment_date_shamsi = $_POST['payment_date'] ?? '';
        $term_id = $_POST['term_id'] ?? 0;
        $description = $_POST['description'] ?? '';
        
        $payment_date = !empty($payment_date_shamsi) ? shamsiToMiladi($payment_date_shamsi) : null;
        
        if ($teacherId > 0 && $amount > 0 && !empty($payment_date)) {
            $data = [
                'teacher_id' => $teacherId,
                'amount' => $amount,
                'payment_date' => $payment_date,
                'term_id' => $term_id,
                'description' => $description,
                'source' => 'manual',
                'created_by' => $user['id']
            ];
            $result = insertData('transactions', $data);
            $message = $result ? '✅ تراکنش ثبت شد.' : '❌ خطا در ثبت.';
        } else {
            $message = '❌ اطلاعات را کامل وارد کنید.';
        }
    } elseif ($action == 'edit') {
        $id = $_POST['id'] ?? 0;
        $amount = $_POST['amount'] ?? 0;
        $payment_date_shamsi = $_POST['payment_date'] ?? '';
        $term_id = $_POST['term_id'] ?? 0;
        $description = $_POST['description'] ?? '';
        
        $payment_date = !empty($payment_date_shamsi) ? shamsiToMiladi($payment_date_shamsi) : null;
        
        if ($id > 0 && $amount > 0 && !empty($payment_date)) {
            $data = [
                'amount' => $amount,
                'payment_date' => $payment_date,
                'term_id' => $term_id,
                'description' => $description
            ];
            $result = updateData('transactions', $data, 'id = :id', ['id' => $id]);
            $message = ($result !== false) ? '✅ تراکنش ویرایش شد.' : '❌ خطا در ویرایش.';
        } else {
            $message = '❌ اطلاعات را کامل وارد کنید.';
        }
    } elseif ($action == 'delete') {
        $id = $_POST['id'] ?? 0;
        if ($id > 0) {
            $result = deleteData('transactions', 'id = :id', ['id' => $id]);
            $message = $result ? '✅ تراکنش حذف شد.' : '❌ خطا در حذف.';
        }
    }
    
    // ===== به‌روزرسانی لیست =====
    if ($selected_teacher_id > 0) {
        $sql = "SELECT t.*, u.name as teacher_name, u.family as teacher_family, tm.name as term_name, tm.code as term_code 
                FROM transactions t 
                LEFT JOIN users u ON t.teacher_id = u.id 
                LEFT JOIN terms tm ON t.term_id = tm.id 
                WHERE t.teacher_id = ?";
        $params = [$selected_teacher_id];
        if ($selected_term_id > 0) {
            $sql .= " AND t.term_id = ?";
            $params[] = $selected_term_id;
        }
        $sql .= " ORDER BY t.payment_date DESC";
        $transactions = fetchAll($sql, $params);
        $totalAmount = 0;
        $termTotals = [];
        foreach ($transactions as $tr) {
            $totalAmount += $tr['amount'];
            $termKey = $tr['term_id'] ?? 0;
            $termName = $tr['term_name'] ?? 'بدون ترم';
            if (!isset($termTotals[$termKey])) {
                $termTotals[$termKey] = ['name' => $termName, 'total' => 0, 'count' => 0];
            }
            $termTotals[$termKey]['total'] += $tr['amount'];
            $termTotals[$termKey]['count']++;
        }
    }
}

$content = 'transactions-content-new.php';
require_once '../includes/layout.php';
?>