<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\TransactionModel;
use App\Models\PointsModel;

class Transaction extends ResourceController
{
    protected $modelName = 'App\Models\TransactionModel';
    protected $format    = 'json';
    protected $db;
    protected $transactionModel;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
        $this->transactionModel = new TransactionModel();
    }

    public function processTransaction()
    {
        $data = $this->request->getJSON(true);
        
        if (!$data || !isset($data['msisdn'], $data['amount'], $data['transaction_id'])) {
            return $this->fail('Missing required fields', 400);
        }

        // Start transaction
        $this->db->transStart();

        try {
            // Check if transaction already exists
            $existingTransaction = $this->transactionModel
                ->where('transaction_id', $data['transaction_id'])
                ->first();

            if ($existingTransaction) {
                return $this->fail('Transaction already processed', 400);
            }

            // Create transaction record
            $transactionData = [
                'msisdn' => $data['msisdn'],
                'amount' => $data['amount'],
                'tip_id' => $data['tip_id'] ?? null,
                'transaction_id' => $data['transaction_id'],
                'naration' => $data['naration'] ?? 'Tips',
                'status' => 0, // Set as pending initially, will be updated by TransactionChecker
                'tip_unlocked' => 0,
                'points_used' => $data['points_used'] ?? 0
            ];

            $transactionId = $this->transactionModel->insert($transactionData);

            // If points were used, deduct them
            if (isset($data['points_used']) && $data['points_used'] > 0) {
                $pointsModel = new PointsModel();
                $pointsModel->usePoints($data['msisdn'], $data['points_used']);
            }

            // If this is a tip purchase, award points
            if (isset($data['tip_id']) && $data['amount'] > 0) {
                $pointsModel = new PointsModel();
                $pointsModel->addPoints($data['msisdn'], $data['amount']);
            }

            $this->db->transComplete();

            return $this->respond([
                'status' => 'pending',
                'message' => 'Transaction recorded and pending confirmation',
                'data' => [
                    'transaction_id' => $transactionId
                ]
            ]);

        } catch (\Exception $e) {
            $this->db->transRollback();
            return $this->fail('Failed to process transaction: ' . $e->getMessage(), 500);
        }
    }
} 