<?php
declare(strict_types=1);
require_once __DIR__ . '/../../app/Config/database.php';

class Ar {
    private PDO $db;
    public function __construct() { $this->db = Database::getConnection(); }

    public function getAll(): array {
        $sql = "SELECT i.*, c.name AS customer_name 
                FROM ar_invoices i 
                JOIN customers c ON i.customer_id = c.id 
                ORDER BY i.invoice_date DESC";
        return $this->db->query($sql)->fetchAll();
    }

    public function getById(int $id): ?array {
        $stmt = $this->db->prepare("SELECT i.*, c.name AS customer_name, c.address, c.email, c.contact_no 
                                    FROM ar_invoices i 
                                    JOIN customers c ON i.customer_id=c.id WHERE i.id=?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function add(array $data): bool {
        $stmt = $this->db->prepare("INSERT INTO ar_invoices (invoice_no,customer_id,invoice_date,due_date,description,subtotal,gst,total_amount,status)
                                    VALUES (?,?,?,?,?,?,?,?,?)");
        return $stmt->execute([
            $data['invoice_no'],$data['customer_id'],$data['invoice_date'],$data['due_date'],$data['description'],
            $data['subtotal'],$data['gst'],$data['total_amount'],$data['status'] ?? 'unpaid'
        ]);
    }

    public function delete(int $id): bool {
        $stmt = $this->db->prepare("DELETE FROM ar_invoices WHERE id=?");
        return $stmt->execute([$id]);
    }

    public function getItems(int $invoice_id): array {
        $stmt = $this->db->prepare("SELECT * FROM ar_invoice_items WHERE invoice_id=?");
        $stmt->execute([$invoice_id]);
        return $stmt->fetchAll();
    }
}
