<?php
require_once 'config.php';

$action = $_GET['action'] ?? '';
$user_id = 1; // Simplification for now, would typically use JWT

switch ($action) {
    case 'login':
        $data = json_decode(file_get_contents('php://input'), true);
        $username = $data['username'] ?? '';
        $password = $data['password'] ?? '';
        
        // Simulating simple auth Check
        // In real app, verify against $pdo with password_verify
        if ($username && $password) {
            sendResponse(['user' => ['id' => 1, 'username' => $username, 'role' => 'Admin']]);
        } else {
            sendResponse(['error' => 'Invalid credentials'], 401);
        }
        break;

    case 'get_dashboard':
        // Calculate dynamic totals
        $stmtTotal = $pdo->query("SELECT SUM(total) as total FROM invoices");
        $totalInvoiced = (float)($stmtTotal->fetch()['total'] ?? 0);

        $stmtOverdue = $pdo->query("SELECT SUM(total) as total FROM invoices WHERE status = 'Overdue'");
        $overdue = (float)($stmtOverdue->fetch()['total'] ?? 0);

        // Fetch recent activity
        $stmtRecent = $pdo->query("SELECT i.id, c.name as title, i.created_at as subtitle, i.total as amount, 'success' as type 
                                    FROM invoices i 
                                    JOIN customers c ON i.customer_id = c.id 
                                    ORDER BY i.created_at DESC LIMIT 3");
        $recent = $stmtRecent->fetchAll();
        foreach ($recent as &$r) {
            $r['title'] = "Invoice INV-" . str_pad($r['id'], 3, '0', STR_PAD_LEFT);
            $r['subtitle'] = $r['subtitle']; // Could format date here
        }

        sendResponse([
            'cashFlow' => [40, 70, 45, 90, 65], // Static for now, hard to trend with few entries
            'totalInvoiced' => $totalInvoiced,
            'overdue' => $overdue,
            'recentActivity' => $recent
        ]);
        break;

    case 'get_invoices':
        $stmt = $pdo->prepare("SELECT i.*, c.name as customer_name FROM invoices i JOIN customers c ON i.customer_id = c.id ORDER BY i.created_at DESC");
        $stmt->execute();
        sendResponse($stmt->fetchAll());
        break;

    case 'get_customers':
        $stmt = $pdo->prepare("SELECT * FROM customers");
        $stmt->execute();
        sendResponse($stmt->fetchAll());
        break;

    case 'get_items':
        $stmt = $pdo->prepare("SELECT * FROM items");
        $stmt->execute();
        sendResponse($stmt->fetchAll());
        break;

    case 'save_customer':
        $data = json_decode(file_get_contents('php://input'), true);
        $name = $data['name'] ?? '';
        $kra_pin = $data['kra_pin'] ?? '';
        
        $stmt = $pdo->prepare("INSERT INTO customers (name, kra_pin) VALUES (?, ?)");
        if ($stmt->execute([$name, $kra_pin])) {
            sendResponse(['success' => true, 'id' => $pdo->lastInsertId()]);
        } else {
            sendResponse(['error' => 'Failed to save customer'], 500);
        }
        break;

    case 'save_item':
        $data = json_decode(file_get_contents('php://input'), true);
        $name = $data['name'] ?? '';
        $price = $data['price'] ?? 0;
        $unit = $data['unit'] ?? '';
        $category = $data['category'] ?? '';

        $stmt = $pdo->prepare("INSERT INTO items (name, price, unit, category) VALUES (?, ?, ?, ?)");
        if ($stmt->execute([$name, $price, $unit, $category])) {
            sendResponse(['success' => true, 'id' => $pdo->lastInsertId()]);
        } else {
            sendResponse(['error' => 'Failed to save item'], 500);
        }
        break;

    case 'save_invoice':
        $data = json_decode(file_get_contents('php://input'), true);
        $customer_id = $data['customer_id'];
        $subtotal = $data['subtotal'] ?? 0;
        $tax_amount = $data['tax_amount'] ?? 0;
        $total = $data['total'];
        $items = $data['items'];

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("INSERT INTO invoices (customer_id, user_id, subtotal, tax_amount, total, status) VALUES (?, ?, ?, ?, ?, 'Draft')");
            $stmt->execute([$customer_id, $user_id, $subtotal, $tax_amount, $total]);
            $invoice_id = $pdo->lastInsertId();

            $stmtItem = $pdo->prepare("INSERT INTO invoice_items (invoice_id, item_id, quantity, unit_price) VALUES (?, ?, ?, ?)");
            foreach ($items as $item) {
                $stmtItem->execute([$invoice_id, $item['id'], $item['qty'], $item['price']]);
            }
            $pdo->commit();
            sendResponse(['success' => true, 'id' => $invoice_id]); // Consistent with other save actions
        } catch (Exception $e) {
            $pdo->rollBack();
            sendResponse(['error' => $e->getMessage()], 500);
        }
        break;

    default:
        sendResponse(['error' => 'Action not found'], 404);
}
?>
