<?php
header('Content-Type: application/json');
session_start();

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$db = new App_DB(DBU::$dba_user);
$input = json_decode(file_get_contents('php://input'), true);
$action = $_GET['action'] ?? $input['action'] ?? '';

switch ($action) {
    case 'get_categories':
        $type = $_GET['type'] ?? '';
        $sql = "SELECT id, category_name, category_type FROM accounts_categories WHERE is_active = 1";
        $params = [];
        if ($type) {
            $sql .= " AND category_type = ?";
            $params[] = $type;
        }
        $res = $db->getRecordSet($sql, $params);
        echo json_encode(['success' => true, 'data' => $res]);
        break;

    case 'get_summary':
        $today = date('Y-m-d');
        $income = $db->getValue("SELECT SUM(amount) FROM accounts_transactions WHERE txn_type = 'income' AND txn_date = ? AND source_module != 'student_fee'", [$today]) ?: 0;
        $expense = $db->getValue("SELECT SUM(amount) FROM accounts_transactions WHERE txn_type = 'expense' AND txn_date = ? AND source_module != 'student_fee'", [$today]) ?: 0;

        $total_income = $db->getValue("SELECT SUM(amount) FROM accounts_transactions WHERE txn_type = 'income' AND source_module != 'student_fee'") ?: 0;
        $total_expense = $db->getValue("SELECT SUM(amount) FROM accounts_transactions WHERE txn_type = 'expense' AND source_module != 'student_fee'") ?: 0;

        echo json_encode([
            'success' => true,
            'today' => ['income' => $income, 'expense' => $expense, 'balance' => $income - $expense],
            'overall' => ['income' => $total_income, 'expense' => $total_expense, 'balance' => $total_income - $total_expense]
        ]);
        break;

    case 'save_transaction':
        $id = $input['id'] ?? null;
        $date = $input['txn_date'] ?? date('Y-m-d');
        $type = $input['txn_type'];
        $cat_id = $input['category_id'];
        $amount = $input['amount'];
        $method = $input['payment_method'] ?? 'Cash';
        $ref = $input['reference_no'] ?? '';
        $desc = $input['description'] ?? '';

        if (!$type || !$cat_id || !$amount) {
            echo json_encode(['success' => false, 'message' => 'Missing required fields']);
            exit;
        }

        if ($id) {
            $sql = "UPDATE accounts_transactions SET txn_date = ?, txn_type = ?, category_id = ?, amount = ?, payment_method = ?, reference_no = ?, description = ? WHERE id = ?";
            $res = $db->dbQuery($sql, [$date, $type, $cat_id, $amount, $method, $ref, $desc, $id]);
        } else {
            $sql = "INSERT INTO accounts_transactions (txn_date, txn_type, category_id, amount, payment_method, reference_no, description, source_module) VALUES (?, ?, ?, ?, ?, ?, ?, 'manual')";
            $res = $db->dbQuery($sql, [$date, $type, $cat_id, $amount, $method, $ref, $desc]);
        }
        echo json_encode(['success' => true, 'message' => 'Transaction saved successfully']);
        break;

    case 'get_transactions':
        $start = $_GET['start_date'] ?? date('Y-m-01');
        $end = $_GET['end_date'] ?? date('Y-m-d');
        $type = $_GET['type'] ?? '';
        $cat = $_GET['category_id'] ?? '';

        $sql = "SELECT t.*, c.category_name 
                FROM accounts_transactions t 
                JOIN accounts_categories c ON t.category_id = c.id 
                WHERE t.txn_date BETWEEN ? AND ?
                AND t.source_module != 'student_fee'";
        $params = [$start, $end];

        if ($type) {
            $sql .= " AND t.txn_type = ?";
            $params[] = $type;
        }
        if ($cat) {
            $sql .= " AND t.category_id = ?";
            $params[] = $cat;
        }
        $sql .= " ORDER BY t.txn_date DESC, t.id DESC";
        $res = $db->getRecordSet($sql, $params);
        echo json_encode(['success' => true, 'data' => $res]);
        break;

    case 'delete_transaction':
        $id = $input['id'];
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'ID missing']);
            exit;
        }
        $db->dbQuery("DELETE FROM accounts_transactions WHERE id = ?", [$id]);
        echo json_encode(['success' => true, 'message' => 'Transaction deleted']);
        break;

    case 'save_category':
        $id = $input['id'] ?? null;
        $name = $input['category_name'];
        $type = $input['category_type'];
        if (!$name || !$type) {
            echo json_encode(['success' => false, 'message' => 'Name and Type required']);
            exit;
        }
        if ($id) {
            $db->dbQuery("UPDATE accounts_categories SET category_name = ?, category_type = ? WHERE id = ?", [$name, $type, $id]);
        } else {
            $db->dbQuery("INSERT INTO accounts_categories (category_name, category_type) VALUES (?, ?)", [$name, $type]);
        }
        echo json_encode(['success' => true, 'message' => 'Category saved successfully']);
        break;

    case 'delete_category':
        $id = $input['id'];
        // Check if category is in use
        $count = $db->getValue("SELECT COUNT(*) FROM accounts_transactions WHERE category_id = ?", [$id]);
        if ($count > 0) {
            echo json_encode(['success' => false, 'message' => 'Category is in use and cannot be deleted']);
            exit;
        }
        $db->dbQuery("DELETE FROM accounts_categories WHERE id = ?", [$id]);
        echo json_encode(['success' => true, 'message' => 'Category deleted']);
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
?>