<?php
/**
 * PaymentAttempt Model
 * Maps to `payment_attempts` table
 */

require_once __DIR__ . '/../Core/Model.php';

class PaymentAttempt extends Model {
    protected string $table = 'payment_attempts';

    public function getAttemptsByPayment(int $paymentId): array {
        $sql = "SELECT pa.*, CONCAT(u.first_name, ' ', u.last_name) as submitted_by_name
                FROM `payment_attempts` pa
                JOIN `users` u ON u.id = pa.submitted_by
                WHERE pa.payment_id = :payment_id
                ORDER BY pa.attempt_no ASC";
        return $this->fetchAll($sql, [':payment_id' => $paymentId]);
    }

    public function getPendingAttemptByPayment(int $paymentId): ?array {
        $sql = "SELECT * FROM `payment_attempts`
                WHERE payment_id = :payment_id AND status = 'pending'
                ORDER BY attempt_no DESC LIMIT 1";
        return $this->fetchOne($sql, [':payment_id' => $paymentId]);
    }

    public function getNextAttemptNo(int $paymentId): int {
        $sql = "SELECT COALESCE(MAX(attempt_no), 0) + 1 FROM `payment_attempts`
                WHERE payment_id = :payment_id";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':payment_id' => $paymentId]);
        return (int)$stmt->fetchColumn();
    }

    public function countAttempts(int $paymentId): int {
        $sql = "SELECT COUNT(*) FROM `payment_attempts` WHERE payment_id = :payment_id";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':payment_id' => $paymentId]);
        return (int)$stmt->fetchColumn();
    }

    public function updateAttemptStatus(int $attemptId, string $status, ?string $rejectReason = null): bool {
        $data = ['status' => $status, 'updated_at' => date('Y-m-d H:i:s')];
        if ($rejectReason !== null) {
            $data['reject_reason'] = $rejectReason;
        }
        return $this->update($attemptId, $data);
    }

    public function hasPendingAttempt(int $paymentId): bool {
        $sql = "SELECT COUNT(*) FROM `payment_attempts`
                WHERE payment_id = :payment_id AND status = 'pending'";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':payment_id' => $paymentId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
