<?php

namespace App\Controllers;

use App\Models\TransactionModel;
use CodeIgniter\API\ResponseTrait;

class Transactions extends BaseController
{
    use ResponseTrait;

    protected $transactionModel;

    public function __construct()
    {
        $this->transactionModel = new TransactionModel();
        date_default_timezone_set('Africa/Kampala');
    }

    public function index()
    {
        // Get date range from GET parameters
        $startDate = $this->request->getGet('start_date');
        $endDate = $this->request->getGet('end_date');

        // Get transaction statistics with date filter if provided
        $builder = $this->transactionModel;
        if ($startDate && $endDate) {
            $builder->where('created_at >=', $startDate . ' 00:00:00')
                   ->where('created_at <=', $endDate . ' 23:59:59');
        }

        $successfulTransactions = $builder->where('status', 'SUCCESS')->findAll();
        $failedTransactions = $builder->where('status', 'FAILED')->findAll();
        
        // Calculate total amounts
        $successfulAmount = array_sum(array_column($successfulTransactions, 'amount'));
        $failedAmount = array_sum(array_column($failedTransactions, 'amount'));
        
        // Count total transactions
        $totalTransactions = count($builder->findAll());

        $data = [
            'title' => 'Transactions',
            'transactions' => $builder->orderBy('created_at', 'DESC')->findAll(),
            'stats' => [
                'successful_amount' => $successfulAmount,
                'failed_amount' => $failedAmount,
                'total_transactions' => $totalTransactions,
                'successful_count' => count($successfulTransactions),
                'failed_count' => count($failedTransactions)
            ],
            'start_date' => $startDate,
            'end_date' => $endDate
        ];

        return view('transactions/index', $data);
    }

    public function filter()
    {
        $status = $this->request->getGet('status');
        $search = $this->request->getGet('search');
        $startDate = $this->request->getGet('start_date');
        $endDate = $this->request->getGet('end_date');

        $builder = $this->transactionModel;

        if ($status && $status !== 'all') {
            $builder->where('status', $status);
        }

        if ($search) {
            $builder->groupStart()
                ->like('msisdn', $search)
                ->orLike('transaction_id', $search)
                ->groupEnd();
        }

        if ($startDate && $endDate) {
            $builder->where('created_at >=', $startDate . ' 00:00:00')
                   ->where('created_at <=', $endDate . ' 23:59:59');
        }

        $transactions = $builder->orderBy('created_at', 'DESC')->findAll();

        return $this->respond($transactions);
    }

    public function updateStatus($id)
    {
        // Get status from POST data
        $status = $this->request->getPost('status');

        // Validate status
        if (!$status || !in_array($status, ['SUCCESS', 'FAILED'])) {
            return $this->fail('Invalid status', 400);
        }

        try {
            // Update the status using transaction_id
            $result = $this->transactionModel->where('transaction_id', $id)->set(['status' => $status])->update();

            if (!$result) {
                return $this->fail('Transaction not found or not updated', 404);
            }

            return $this->respond(['message' => 'Status updated successfully']);
        } catch (\Exception $e) {
            return $this->fail('Failed to update status: ' . $e->getMessage(), 500);
        }
    }

    public function export()
    {
        $status = $this->request->getGet('status');
        $startDate = $this->request->getGet('start_date');
        $endDate = $this->request->getGet('end_date');

        $builder = $this->transactionModel;

        if ($status && $status !== 'all') {
            $builder->where('status', $status);
        }

        if ($startDate && $endDate) {
            $builder->where('created_at >=', $startDate . ' 00:00:00')
                   ->where('created_at <=', $endDate . ' 23:59:59');
        }

        $transactions = $builder->orderBy('created_at', 'DESC')->findAll();

        // Create Excel file
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Set headers
        $sheet->setCellValue('A1', 'Transaction ID');
        $sheet->setCellValue('B1', 'Reference');
        $sheet->setCellValue('C1', 'Phone Number');
        $sheet->setCellValue('D1', 'Amount');
        $sheet->setCellValue('E1', 'Status');
        $sheet->setCellValue('F1', 'Created At');

        // Add data
        $row = 2;
        foreach ($transactions as $transaction) {
            $sheet->setCellValue('A' . $row, $transaction['transaction_id']);
            $sheet->setCellValue('B' . $row, $transaction['reference']);
            $sheet->setCellValue('C' . $row, $transaction['msisdn']);
            $sheet->setCellValue('D' . $row, $transaction['amount']);
            $sheet->setCellValue('E' . $row, $transaction['status']);
            $sheet->setCellValue('F' . $row, $transaction['created_at']);
            $row++;
        }

        // Create writer
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        
        // Set headers for download
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="transactions_' . date('Y-m-d') . '.xlsx"');
        header('Cache-Control: max-age=0');

        // Save file to PHP output
        $writer->save('php://output');
        exit;
    }
}
