<?php
// admin/transactions.php - مدیریت تراکنش‌ها

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 = 'ثبت و مدیریت مبالغ واریزی به اساتید';

$teachers = getAllTeachers();
$allTerms = getAllTerms();

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $teacherId = $_POST['teacher_id'] ?? 0;
    $amount = $_POST['amount'] ?? 0;
    $payment_date = $_POST['payment_date'] ?? '';
    $term_id = $_POST['term_id'] ?? 0;
    $description = $_POST['description'] ?? '';
    
    if ($teacherId > 0 && $amount > 0 && !empty($payment_date)) {
        $data = [
            'teacher_id' => $teacherId,
            'amount' => $amount,
            'payment_date' => $payment_date,
            'term_id' => $term_id,
            'description' => $description,
            'created_by' => $user['id']
        ];
        $result = createTransaction($data);
        if ($result) {
            $message = 'تراکنش با موفقیت ثبت شد.';
        } else {
            $message = 'خطا در ثبت تراکنش.';
        }
    } else {
        $message = 'اطلاعات را کامل وارد کنید.';
    }
}

$transactions = fetchAll(
    "SELECT t.*, u.name, u.family, u.national_code, tm.name as term_name
     FROM transactions t 
     LEFT JOIN users u ON t.teacher_id = u.id 
     LEFT JOIN terms tm ON t.term_id = tm.id
     ORDER BY t.payment_date DESC"
);

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