<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Url;
use App\Models\PaymentRequest;
use App\Models\LoanRepayment;
use App\Helpers\PaymentGateway;
use App\Helpers\Mailer;

class PaymentRequestController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        if (Auth::user()->role !== 'admin') { $_SESSION['error'] = 'Unauthorized'; $this->redirect('/'); }
        $model = new PaymentRequest();
        $page = max(1, (int)($_GET['page'] ?? 1));
        $requests = $model->getAll($page, 50);
        $this->view('payments/requests', ['requests' => $requests]);
    }

    public function resend($params)
    {
        if (Auth::user()->role !== 'admin') { $_SESSION['error'] = 'Unauthorized'; $this->redirect('/'); }
        $id = $params['id'] ?? 0;
        $model = new PaymentRequest();
        $stmt = $this->db->prepare("SELECT * FROM payment_requests WHERE id = ?");
        $stmt->execute([$id]);
        $req = $stmt->fetch(\PDO::FETCH_OBJ);
        if (!$req) { $_SESSION['error'] = 'Request not found'; $this->redirect('/payments/requests'); }

        // Re-initiate if still pending
        if ($req->status === 'pending') {
            $repModel = new LoanRepayment();
            $rep = $repModel->find($req->loan_repayment_id);
            $userStmt = $this->db->prepare("SELECT email FROM users WHERE id = ?");
            $userStmt->execute([$req->user_id]);
            $u = $userStmt->fetch(\PDO::FETCH_OBJ);

            if ($u) {
                $reference = 'loan_lr_' . $req->loan_repayment_id . '_' . time();
                $callback = Url::to('/payment/callback');
                $init = PaymentGateway::initPaystackPayment($u->email, $req->amount, $reference, $callback);
                if (!empty($init['success']) && !empty($init['authorization_url'])) {
                    $this->db->prepare("UPDATE payment_requests SET reference = ?, authorization_url = ?, updated_at = NOW() WHERE id = ?")->execute([$reference, $init['authorization_url'], $id]);
                    Mailer::send($u->email, 'Loan Payment Link', "Please pay your loan repayment: <a href='{$init['authorization_url']}'>Pay Now</a>");
                    $_SESSION['success'] = 'Payment link resent';
                } else {
                    $_SESSION['error'] = 'Could not initialize payment link: ' . ($init['message'] ?? '');
                }
            }
        } else {
            $_SESSION['error'] = 'Request not pending';
        }

        $this->redirect('/payments/requests');
    }
}
