<?php

namespace App\Models;

use App\Core\Model;

class PaymentRequest extends Model
{
    protected $table = 'payment_requests';
    protected $primaryKey = 'id';

    public function createRequest($data)
    {
        $stmt = $this->db->prepare("INSERT INTO {$this->table} (user_id, loan_repayment_id, gateway, reference, authorization_url, amount, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->execute([
            $data['user_id'] ?? null,
            $data['loan_repayment_id'] ?? null,
            $data['gateway'] ?? null,
            $data['reference'] ?? null,
            $data['authorization_url'] ?? null,
            $data['amount'] ?? 0,
            $data['status'] ?? 'pending',
        ]);
        return $this->db->lastInsertId();
    }

    public function getAll($page = 1, $perPage = 50)
    {
        $offset = ($page - 1) * $perPage;
        $stmt = $this->db->prepare("SELECT pr.*, u.name, u.email, lr.due_date FROM {$this->table} pr LEFT JOIN users u ON pr.user_id = u.id LEFT JOIN loan_repayments lr ON pr.loan_repayment_id = lr.id ORDER BY pr.created_at DESC LIMIT ? OFFSET ?");
        $stmt->execute([$perPage, $offset]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function findByReference($reference)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE reference = ? LIMIT 1");
        $stmt->execute([$reference]);
        return $stmt->fetch(\PDO::FETCH_OBJ);
    }

    public function updateStatus($id, $status)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET status = ?, updated_at = NOW() WHERE id = ?");
        return $stmt->execute([$status, $id]);
    }
}
