<?php
require_once __DIR__ . '/../db/config.php';

function get_journal_entries() {
    $db = db();
    $stmt = $db->query("SELECT j.*, SUM(e.debit) as total_debit, SUM(e.credit) as total_credit 
                        FROM accounting_journal j 
                        LEFT JOIN accounting_entries e ON j.id = e.journal_id 
                        GROUP BY j.id ORDER BY j.date DESC");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function get_full_ledger() {
    $db = db();
    $stmt = $db->query("SELECT j.id, j.date, j.description, j.reference, e.account_name, e.debit, e.credit 
                        FROM accounting_journal j 
                        JOIN accounting_entries e ON j.id = e.journal_id 
                        ORDER BY j.date DESC, j.id DESC");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function get_full_ledger_filtered($search = '', $date_from = '', $date_to = '') {
    $db = db();
    $sql = "SELECT j.id, j.date, j.description, j.reference, e.account_name, e.debit, e.credit 
            FROM accounting_journal j 
            JOIN accounting_entries e ON j.id = e.journal_id 
            WHERE 1=1";
    $params = [];
    
    if ($search) {
        $sql .= " AND (j.description LIKE ? OR j.reference LIKE ? OR e.account_name LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    if ($date_from) {
        $sql .= " AND j.date >= ?";
        $params[] = $date_from;
    }
    if ($date_to) {
        $sql .= " AND j.date <= ?";
        $params[] = $date_to;
    }
    
    $sql .= " ORDER BY j.date DESC, j.id DESC";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function get_ledger_count($search = '', $date_from = '', $date_to = '') {
    $db = db();
    $sql = "SELECT COUNT(*) 
            FROM accounting_journal j 
            JOIN accounting_entries e ON j.id = e.journal_id 
            WHERE 1=1";
    $params = [];
    
    if ($search) {
        $sql .= " AND (j.description LIKE ? OR j.reference LIKE ? OR e.account_name LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    if ($date_from) {
        $sql .= " AND j.date >= ?";
        $params[] = $date_from;
    }
    if ($date_to) {
        $sql .= " AND j.date <= ?";
        $params[] = $date_to;
    }
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchColumn();
}

function get_ledger_paginated($search = '', $date_from = '', $date_to = '', $limit = 10, $offset = 0) {
    $db = db();
    $sql = "SELECT j.id, j.date, j.description, j.reference, e.account_name, e.debit, e.credit 
            FROM accounting_journal j 
            JOIN accounting_entries e ON j.id = e.journal_id 
            WHERE 1=1";
    $params = [];
    
    if ($search) {
        $sql .= " AND (j.description LIKE ? OR j.reference LIKE ? OR e.account_name LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    if ($date_from) {
        $sql .= " AND j.date >= ?";
        $params[] = $date_from;
    }
    if ($date_to) {
        $sql .= " AND j.date <= ?";
        $params[] = $date_to;
    }
    
    $sql .= " ORDER BY j.date DESC, j.id DESC LIMIT $limit OFFSET $offset";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function get_trial_balance() {
    $db = db();
    $stmt = $db->query("SELECT account_name, SUM(debit) as total_debit, SUM(credit) as total_credit 
                        FROM accounting_entries 
                        GROUP BY account_name");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function get_balance_sheet() {
    $db = db();
    $stmt = $db->query("SELECT a.name, a.type, SUM(e.debit - e.credit) as balance 
                        FROM accounting_accounts a
                        LEFT JOIN accounting_entries e ON a.name = e.account_name
                        GROUP BY a.name, a.type");
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $sheet = ['أصول' => 0, 'خصوم' => 0, 'حقوق ملكية' => 0, 'إيرادات' => 0, 'مصروفات' => 0];
    foreach($data as $row) {
        if (isset($sheet[$row['type']])) {
            $sheet[$row['type']] += $row['balance'];
        }
    }
    return $sheet;
}

function get_all_accounts() {
    return db()->query("SELECT * FROM accounting_accounts ORDER BY type, name")->fetchAll(PDO::FETCH_ASSOC);
}

function add_journal_entry($date, $description, $reference, $entries) {
    $db = db();
    $db->beginTransaction();
    try {
        $stmt = $db->prepare("INSERT INTO accounting_journal (date, description, reference) VALUES (?, ?, ?)");
        $stmt->execute([$date, $description, $reference]);
        $journal_id = $db->lastInsertId();

        $stmt = $db->prepare("INSERT INTO accounting_entries (journal_id, account_name, debit, credit) VALUES (?, ?, ?, ?)");
        foreach ($entries as $entry) {
            $stmt->execute([$journal_id, $entry['account'], $entry['debit'], $entry['credit']]);
        }
        $db->commit();
        return $journal_id;
    } catch (Exception $e) {
        $db->rollBack();
        return false;
    }
}

function delete_journal_entry($id) {
    $db = db();
    $db->beginTransaction();
    try {
        $stmt = $db->prepare("DELETE FROM accounting_entries WHERE journal_id = ?");
        $stmt->execute([$id]);
        
        $stmt = $db->prepare("DELETE FROM accounting_journal WHERE id = ?");
        $stmt->execute([$id]);
        
        $db->commit();
        return true;
    } catch (Exception $e) {
        $db->rollBack();
        return false;
    }
}

function get_journal_entry_details($id) {
    $db = db();
    $stmt = $db->prepare("SELECT * FROM accounting_journal WHERE id = ?");
    $stmt->execute([$id]);
    $journal = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$journal) return null;
    
    $stmt = $db->prepare("SELECT * FROM accounting_entries WHERE journal_id = ? ORDER BY id ASC");
    $stmt->execute([$id]);
    $entries = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $debit_account = '';
    $credit_account = '';
    $amount = 0;
    
    foreach ($entries as $e) {
        if ($e['debit'] > 0) {
            $debit_account = $e['account_name'];
            $amount = $e['debit'];
        } elseif ($e['credit'] > 0) {
            $credit_account = $e['account_name'];
            if ($amount == 0) $amount = $e['credit'];
        }
    }
    
    return [
        'id' => $journal['id'],
        'date' => $journal['date'],
        'description' => $journal['description'],
        'reference' => $journal['reference'],
        'debit_account' => $debit_account,
        'credit_account' => $credit_account,
        'amount' => $amount
    ];
}

function edit_journal_entry($id, $date, $description, $reference, $entries) {
    $db = db();
    $db->beginTransaction();
    try {
        $stmt = $db->prepare("UPDATE accounting_journal SET date = ?, description = ?, reference = ? WHERE id = ?");
        $stmt->execute([$date, $description, $reference, $id]);

        $stmt = $db->prepare("DELETE FROM accounting_entries WHERE journal_id = ?");
        $stmt->execute([$id]);

        $stmt = $db->prepare("INSERT INTO accounting_entries (journal_id, account_name, debit, credit) VALUES (?, ?, ?, ?)");
        foreach ($entries as $entry) {
            $stmt->execute([$id, $entry['account'], $entry['debit'], $entry['credit']]);
        }
        $db->commit();
        return true;
    } catch (Exception $e) {
        $db->rollBack();
        return false;
    }
}
?>