<?php
ob_start(); // Catch any stray output/warnings before JSON
// ============================================================
// Unified API for: suppliers, expenses, income, accounts, account_type
// ============================================================
require_once __DIR__ . '/../core/auth.php';
require_once __DIR__ . '/../core/response.php';
cors();
$user = Auth::requireToken();
$db   = DB::get();

$module = $_GET['module'] ?? $_POST['module'] ?? '';
$act    = $_GET['action'] ?? $_POST['action'] ?? 'list';

try {
    switch ($module) {

        // ────── SUPPLIERS ──────
        case 'suppliers':
            if ($act === 'list') {
                $q = '%' . $db->esc($_GET['q'] ?? '') . '%';
                json_ok($db->select("SELECT * FROM suppliers WHERE suppliers_name LIKE ? ORDER BY suppliers_name ASC", 's', $q));
            } elseif ($act === 'get') {
                $id = (int)($_GET['id'] ?? 0);
                json_ok($db->selectOne("SELECT * FROM suppliers WHERE record_id = ?", 'i', $id));
            } elseif ($act === 'add') {
                $name = trim($_POST['suppliers_name'] ?? '');
                if (!$name) json_err('Name required');
                $id = $db->execute("INSERT INTO suppliers (suppliers_name) VALUES (?)", 's', $name);
                Auth::log((int)$user['user_id'], "ADDED SUPPLIER: $name", 'suppliers', $id);
                json_ok(['id' => $id], 'Supplier added');
            } elseif ($act === 'update') {
                $id = (int)($_POST['id'] ?? 0);
                $name = trim($_POST['suppliers_name'] ?? '');
                $db->execute("UPDATE suppliers SET suppliers_name=? WHERE record_id=?", 'si', $name, $id);
                Auth::log((int)$user['user_id'], "UPDATED SUPPLIER: $name", 'suppliers', $id);
                json_ok(null, 'Updated');
            }
            break;

        // ────── EXPENSES ──────
        case 'expenses':
            if ($act === 'list') {
                $rows = $db->select(
                    "SELECT e.*, a.accounts_name, s.suppliers_name
                     FROM expenses e
                     LEFT JOIN accounts a ON a.record_id = e.accounts_id
                     LEFT JOIN suppliers s ON s.record_id = e.suppliers_id
                     ORDER BY e.record_id DESC"
                );
                json_ok($rows);
            } elseif ($act === 'add') {
                $acctId  = (int)($_POST['accounts_id'] ?? 0);
                $suppId  = (int)($_POST['suppliers_id'] ?? 0);
                $amount  = (float)($_POST['amount'] ?? 0);
                $desc    = trim($_POST['description'] ?? '');
                $invNum  = trim($_POST['invoice_number'] ?? '');
                $date    = trim($_POST['date'] ?? date('Y-m-d'));
                $id = $db->execute(
                    "INSERT INTO expenses (accounts_id, amount, description, invoice_number, date, suppliers_id) VALUES (?,?,?,?,?,?)",
                    'idsssi', $acctId, $amount, $desc, $invNum, $date, $suppId
                );
                Auth::log((int)$user['user_id'], "ADDED EXPENSE: $desc R$amount", 'expenses', $id);
                json_ok(['id' => $id], 'Expense added');
            } elseif ($act === 'update') {
                $id     = (int)($_POST['id'] ?? 0);
                $acctId = (int)($_POST['accounts_id'] ?? 0);
                $suppId = (int)($_POST['suppliers_id'] ?? 0);
                $amount = (float)($_POST['amount'] ?? 0);
                $desc   = trim($_POST['description'] ?? '');
                $invNum = trim($_POST['invoice_number'] ?? '');
                $date   = trim($_POST['date'] ?? '');
                $db->execute(
                    "UPDATE expenses SET accounts_id=?, amount=?, description=?, invoice_number=?, date=?, suppliers_id=? WHERE record_id=?",
                    'idsssis', $acctId, $amount, $desc, $invNum, $date, $suppId, $id
                );
                Auth::log((int)$user['user_id'], "UPDATED EXPENSE #$id", 'expenses', $id);
                json_ok(null, 'Updated');
            }
            break;

        // ────── INCOME ──────
        case 'income':
            if ($act === 'list') {
                $rows = $db->select(
                    "SELECT i.*, a.accounts_name, inv.invoice_no, inv.clients_id, c.clients_name
                     FROM income i
                     LEFT JOIN accounts a ON a.record_id = i.accounts_id
                     LEFT JOIN invoices inv ON inv.record_id = i.invoices_id
                     LEFT JOIN clients c ON c.record_id = inv.clients_id
                     ORDER BY i.record_id DESC"
                );
                json_ok($rows);
            } elseif ($act === 'add') {
                $acctId = (int)($_POST['accounts_id'] ?? 0);
                $invId  = (int)($_POST['invoices_id'] ?? 0);
                $amount = (float)($_POST['amount'] ?? 0);
                $date   = trim($_POST['date_created'] ?? date('Y-m-d'));
                $id = $db->execute(
                    "INSERT INTO income (accounts_id, amount, date_created, invoices_id) VALUES (?,?,?,?)",
                    'idsi', $acctId, $amount, $date, $invId
                );
                Auth::log((int)$user['user_id'], "ADDED INCOME R$amount", 'income', $id);
                json_ok(['id' => $id], 'Income added');
            } elseif ($act === 'update') {
                $id     = (int)($_POST['id'] ?? 0);
                $acctId = (int)($_POST['accounts_id'] ?? 0);
                $invId  = (int)($_POST['invoices_id'] ?? 0);
                $amount = (float)($_POST['amount'] ?? 0);
                $date   = trim($_POST['date_created'] ?? '');
                $db->execute(
                    "UPDATE income SET accounts_id=?, amount=?, date_created=?, invoices_id=? WHERE record_id=?",
                    'idsii', $acctId, $amount, $date, $invId, $id
                );
                json_ok(null, 'Updated');
            } elseif ($act === 'delete') {
                $id    = (int)($_POST['id'] ?? 0);
                $invId = (int)($_POST['invoices_id'] ?? 0);
                if (!$id) json_err('ID required');
                $db->execute("DELETE FROM income WHERE record_id = ?", 'i', $id);
                // Recalculate linked invoice status if applicable
                if ($invId) {
                    $invoice   = $db->selectOne("SELECT total FROM invoices WHERE record_id = ?", 'i', $invId);
                    $totalPaid = $db->selectOne("SELECT COALESCE(SUM(amount),0) AS paid FROM income WHERE invoices_id = ?", 'i', $invId);
                    $paid = (float)$totalPaid['paid'];
                    $inv  = (float)($invoice['total'] ?? 0);
                    if ($paid <= 0)       $newStatus = 'APPROVED';
                    elseif ($paid < $inv) $newStatus = 'PARTIALLY PAID';
                    else                  $newStatus = 'PAID';
                    $db->execute("UPDATE invoices SET status=? WHERE record_id=?", 'si', $newStatus, $invId);
                }
                Auth::log((int)$user['user_id'], "DELETED INCOME #$id", 'income', $id);
                json_ok(null, 'Deleted');
            }
            break;

        // ────── ACCOUNTS ──────
        case 'accounts':
            if ($act === 'list') {
                $rows = $db->select(
                    "SELECT a.*, at.account_type_name, at.expence_or_income
                     FROM accounts a
                     LEFT JOIN account_type at ON at.record_id = a.account_type_id
                     ORDER BY a.accounts_name ASC"
                );
                json_ok($rows);
            } elseif ($act === 'add') {
                $name   = trim($_POST['accounts_name'] ?? '');
                $typeId = (int)($_POST['account_type_id'] ?? 0);
                if (!$name) json_err('Name required');
                $id = $db->execute("INSERT INTO accounts (accounts_name, account_type_id) VALUES (?,?)", 'si', $name, $typeId);
                Auth::log((int)$user['user_id'], "ADDED ACCOUNT: $name", 'accounts', $id);
                json_ok(['id' => $id], 'Account added');
            } elseif ($act === 'update') {
                $id     = (int)($_POST['id'] ?? 0);
                $name   = trim($_POST['accounts_name'] ?? '');
                $typeId = (int)($_POST['account_type_id'] ?? 0);
                $db->execute("UPDATE accounts SET accounts_name=?, account_type_id=? WHERE record_id=?", 'sii', $name, $typeId, $id);
                json_ok(null, 'Updated');
            }
            break;

        // ────── ACCOUNT TYPES ──────
        case 'account_type':
            if ($act === 'list') {
                json_ok($db->select("SELECT * FROM account_type ORDER BY account_type_name ASC"));
            } elseif ($act === 'add') {
                $name = trim($_POST['account_type_name'] ?? '');
                $ei   = trim($_POST['expence_or_income'] ?? 'EXPENCE');
                $id = $db->execute("INSERT INTO account_type (account_type_name, expence_or_income) VALUES (?,?)", 'ss', $name, $ei);
                json_ok(['id' => $id], 'Type added');
            }
            break;

        // ────── REPORTS ──────
        case 'reports':
            if ($act === 'profit') {
                $from = $db->esc($_GET['from'] ?? date('Y-01-01'));
                $to   = $db->esc($_GET['to']   ?? date('Y-12-31'));
                $income   = $db->selectOne("SELECT COALESCE(SUM(amount),0) as total FROM income WHERE date_created BETWEEN '$from' AND '$to'");
                $expenses = $db->selectOne("SELECT COALESCE(SUM(amount),0) as total FROM expenses WHERE date BETWEEN '$from' AND '$to'");
                $profit   = ($income['total'] ?? 0) - ($expenses['total'] ?? 0);
                json_ok([
                    'income'   => (float)$income['total'],
                    'expenses' => (float)$expenses['total'],
                    'profit'   => $profit,
                    'from'     => $from,
                    'to'       => $to,
                ]);
            } elseif ($act === 'dashboard') {
                $totalClients   = $db->selectOne("SELECT COUNT(*) as c FROM clients")['c'] ?? 0;
                $totalInvoices  = $db->selectOne("SELECT COUNT(*) as c FROM invoices")['c'] ?? 0;
                $unpaidInvoices = $db->selectOne("SELECT COUNT(*) as c FROM invoices WHERE status != 'PAID'")['c'] ?? 0;
                $totalIncome    = $db->selectOne("SELECT COALESCE(SUM(amount),0) as t FROM income")['t'] ?? 0;
                $totalExpenses  = $db->selectOne("SELECT COALESCE(SUM(amount),0) as t FROM expenses")['t'] ?? 0;
                $recentInvoices = $db->select(
                    "SELECT i.*, c.clients_name FROM invoices i LEFT JOIN clients c ON c.record_id = i.clients_id ORDER BY i.record_id DESC LIMIT 5"
                );
                $recentQuotes = $db->select(
                    "SELECT q.*, c.clients_name FROM quotes q LEFT JOIN clients c ON c.record_id = q.clients_id ORDER BY q.record_id DESC LIMIT 5"
                );
                json_ok([
                    'clients'        => (int)$totalClients,
                    'invoices'       => (int)$totalInvoices,
                    'unpaid'         => (int)$unpaidInvoices,
                    'income'         => (float)$totalIncome,
                    'expenses'       => (float)$totalExpenses,
                    'profit'         => (float)$totalIncome - (float)$totalExpenses,
                    'recent_invoices'=> $recentInvoices,
                    'recent_quotes'  => $recentQuotes,
                ]);
            } elseif ($act === 'logs') {
                $rows = $db->select(
                    "SELECT l.*, u.username FROM logs l LEFT JOIN proart_accounting_users u ON u.record_id = l.proart_accounting_users_id ORDER BY l.record_id DESC LIMIT 200"
                );
                json_ok($rows);
            }
            break;

        // ────── COMPANY ──────
        case 'company':
            if ($act === 'get') {
                $co = $db->selectOne("SELECT * FROM company WHERE record_id = 1");
                json_ok($co);
            } elseif ($act === 'update') {
                $f = fn($k) => trim($_POST[$k] ?? '');
                $db->execute(
                    "UPDATE company SET company_name=?, reg_no=?, email=?, phone=?, address=?, bank=?, acc=?, branch=?, Tc_Cs=? WHERE record_id=1",
                    'sssssssss', $f('company_name'), $f('reg_no'), $f('email'), $f('phone'), $f('address'), $f('bank'), $f('acc'), $f('branch'), $f('Tc_Cs')
                );
                json_ok(null, 'Company updated');
            }
            break;

        // ────── USERS ──────
        case 'users':
            if ($act === 'list') {
                json_ok($db->select("SELECT record_id, username, email, rights FROM proart_accounting_users ORDER BY username ASC"));
            } elseif ($act === 'add') {
                $uname = trim($_POST['username'] ?? '');
                $pass  = trim($_POST['password'] ?? '');
                $email = trim($_POST['email'] ?? '');
                $rights = trim($_POST['rights'] ?? 'user');
                if (!$uname || !$pass) json_err('Username and password required');
                $id = $db->execute(
                    "INSERT INTO proart_accounting_users (username, password, email, rights) VALUES (?, SHA2(?,256), ?, ?)",
                    'ssss', $uname, $pass, $email, $rights
                );
                json_ok(['id' => $id], 'User added');
            } elseif ($act === 'update') {
                $id    = (int)($_POST['id'] ?? 0);
                $email = trim($_POST['email'] ?? '');
                $rights = trim($_POST['rights'] ?? 'user');
                $db->execute("UPDATE proart_accounting_users SET email=?, rights=? WHERE record_id=?", 'ssi', $email, $rights, $id);
                json_ok(null, 'Updated');
            } elseif ($act === 'change_password') {
                $id   = (int)($_POST['id'] ?? 0);
                $pass = trim($_POST['password'] ?? '');
                if (!$pass) json_err('Password required');
                $db->execute("UPDATE proart_accounting_users SET password=SHA2(?,256) WHERE record_id=?", 'si', $pass, $id);
                json_ok(null, 'Password changed');
            }
            break;

        // ────── LOOKUPS ──────
        case 'lookups':
            json_ok([
                'clients'      => $db->select("SELECT record_id, clients_name FROM clients ORDER BY clients_name ASC"),
                'suppliers'    => $db->select("SELECT record_id, suppliers_name FROM suppliers ORDER BY suppliers_name ASC"),
                'accounts'     => $db->select("SELECT record_id, accounts_name, account_type_id FROM accounts ORDER BY accounts_name ASC"),
                'account_types'=> $db->select("SELECT * FROM account_type ORDER BY account_type_name ASC"),
                'provinces'    => $db->select("SELECT * FROM province ORDER BY province_name ASC"),
                'countries'    => $db->select("SELECT * FROM country ORDER BY country_name ASC"),
                'quotes'       => $db->select("SELECT record_id, quote_no, quotes_name FROM quotes ORDER BY quote_no DESC"),
                'invoices'     => $db->select("SELECT record_id, invoice_no FROM invoices ORDER BY invoice_no DESC"),
            ]);
            break;

        default:
            json_err('Unknown module: ' . $module);
    }
} catch (Exception $e) {
    json_err($e->getMessage(), 500);
}