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

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

    public function getBills(): array {
        $sql = "SELECT b.*, v.name AS vendor_name
                FROM ap_bills b
                JOIN vendors v ON v.id=b.vendor_id
                ORDER BY b.bill_date DESC";
        return $this->db->query($sql)->fetchAll();
    }

    public function getBill(int $id): ?array {
        $stmt = $this->db->prepare("SELECT b.*, v.name AS vendor_name, v.address, v.gst_no
                                    FROM ap_bills b
                                    JOIN vendors v ON v.id=b.vendor_id
                                    WHERE b.id=?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function addBill(array $data): bool {
        $sql="INSERT INTO ap_bills(bill_no,vendor_id,bill_date,due_date,total_amount,gst_amount,status,remarks)
              VALUES(?,?,?,?,?,?,?,?)";
        $stmt=$this->db->prepare($sql);
        return $stmt->execute([
            $data['bill_no'],$data['vendor_id'],$data['bill_date'],$data['due_date'],
            $data['total_amount'],$data['gst_amount'],'unpaid',$data['remarks']
        ]);
    }

    public function updateBill(int $id,array $data): bool {
        $sql="UPDATE ap_bills SET bill_no=?,vendor_id=?,bill_date=?,due_date=?,total_amount=?,gst_amount=?,remarks=? WHERE id=?";
        $stmt=$this->db->prepare($sql);
        return $stmt->execute([
            $data['bill_no'],$data['vendor_id'],$data['bill_date'],$data['due_date'],
            $data['total_amount'],$data['gst_amount'],$data['remarks'],$id
        ]);
    }

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

    public function addPayment(array $data): bool {
        $sql="INSERT INTO ap_payments(bill_id,payment_date,amount,method,reference_no,remarks)
              VALUES(?,?,?,?,?,?)";
        $stmt=$this->db->prepare($sql);
        return $stmt->execute([
            $data['bill_id'],$data['payment_date'],$data['amount'],
            $data['method'],$data['reference_no'],$data['remarks']
        ]);
    }

    public function getPayments(int $billId): array {
        $stmt=$this->db->prepare("SELECT * FROM ap_payments WHERE bill_id=? ORDER BY payment_date DESC");
        $stmt->execute([$billId]);
        return $stmt->fetchAll();
    }
}
