<?php

class Payment extends Model {

    public function addPayment($data) {
        $stmt = $this->db->prepare("
            INSERT INTO payments (invoice_id, amount, payment_date, method, reference)
            VALUES (:invoice_id, :amount, :payment_date, :method, :reference)
        ");
        return $stmt->execute([
            ':invoice_id'   => $data['invoice_id'],
            ':amount'       => $data['amount'],
            ':payment_date' => $data['payment_date'],
            ':method'       => $data['method'],
            ':reference'    => $data['reference'] ?? null
        ]);
    }

    public function getPaymentsByInvoiceId($invoice_id) {
        $stmt = $this->db->prepare("
            SELECT * FROM payments 
            WHERE invoice_id = :invoice_id 
            ORDER BY payment_date DESC
        ");
        $stmt->execute([':invoice_id' => $invoice_id]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getPaymentById($id) {
        $stmt = $this->db->prepare("SELECT * FROM payments WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function updatePayment($id, $data) {
        $stmt = $this->db->prepare("
            UPDATE payments SET
                invoice_id = :invoice_id,
                amount = :amount,
                payment_date = :payment_date,
                method = :method,
                reference = :reference
            WHERE id = :id
        ");
        return $stmt->execute([
            ':id'           => $id,
            ':invoice_id'   => $data['invoice_id'],
            ':amount'       => $data['amount'],
            ':payment_date' => $data['payment_date'],
            ':method'       => $data['method'],
            ':reference'    => $data['reference'] ?? null
        ]);
    }

    public function deletePayment($id) {
        $stmt = $this->db->prepare("DELETE FROM payments WHERE id = :id");
        return $stmt->execute([':id' => $id]);
    }

    public function getTotalPaidByInvoiceId($invoice_id) {
        $stmt = $this->db->prepare("
            SELECT COALESCE(SUM(amount), 0) AS total_paid 
            FROM payments 
            WHERE invoice_id = :invoice_id
        ");
        $stmt->execute([':invoice_id' => $invoice_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ? $row['total_paid'] : 0;
    }
}
