<?php
/**
 * Payments API Routes
 * 
 * Handles payment processing and payment management.
 */

require_once '../lib/Auth.php';
require_once '../lib/Validation.php';

$auth = new Auth();
$validation = new Validation();
$response = new Response();
$db = getDB();

// Get request data
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$id = $_GET['id'] ?? null;
$action = $_GET['action'] ?? '';

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if ($id) {
            // Get single payment
            $stmt = $db->prepare("
                SELECT p.*, o.order_number, o.customer_name, o.total_amount 
                FROM payments p 
                JOIN orders o ON p.order_id = o.id 
                WHERE p.id = ?
            ");
            $stmt->execute([$id]);
            $payment = $stmt->fetch();
            
            if (!$payment) {
                $response->notFound('Payment not found');
            }
            
            $response->success($payment);
            
        } else {
            // Get all payments with filtering and pagination
            $page = max(1, intval($_GET['page'] ?? 1));
            $limit = min(50, max(1, intval($_GET['limit'] ?? 20)));
            $offset = ($page - 1) * $limit;
            
            $status = $_GET['status'] ?? null;
            $method = $_GET['method'] ?? null;
            $date_from = $_GET['date_from'] ?? null;
            $date_to = $_GET['date_to'] ?? null;
            
            $where_conditions = [];
            $params = [];
            
            if ($status) {
                $where_conditions[] = "p.status = ?";
                $params[] = $status;
            }
            
            if ($method) {
                $where_conditions[] = "p.payment_method = ?";
                $params[] = $method;
            }
            
            if ($date_from) {
                $where_conditions[] = "DATE(p.created_at) >= ?";
                $params[] = $date_from;
            }
            
            if ($date_to) {
                $where_conditions[] = "DATE(p.created_at) <= ?";
                $params[] = $date_to;
            }
            
            $where_clause = $where_conditions ? "WHERE " . implode(' AND ', $where_conditions) : "";
            
            // Get payments
            $stmt = $db->prepare("
                SELECT p.*, o.order_number, o.customer_name 
                FROM payments p 
                JOIN orders o ON p.order_id = o.id 
                $where_clause 
                ORDER BY p.created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);
            $payments = $stmt->fetchAll();
            
            // Get total count
            $stmt = $db->prepare("SELECT COUNT(*) as total FROM payments p $where_clause");
            $count_params = array_slice($params, 0, count($params) - 2);
            $stmt->execute($count_params);
            $total = $stmt->fetch()['total'];
            
            $response->success([
                'payments' => $payments,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $total,
                    'pages' => ceil($total / $limit)
                ]
            ]);
        }
        break;
        
    case 'POST':
        // Process payment - any authenticated user can process payments
        $user_data = $auth->protectRoute();
        
        $validation_result = $validation->validatePayment($input);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        try {
            // Verify order exists and amount matches
            $stmt = $db->prepare("SELECT id, total_amount, status FROM orders WHERE id = ?");
            $stmt->execute([$input['order_id']]);
            $order = $stmt->fetch();
            
            if (!$order) {
                $response->notFound('Order not found');
            }
            
            if ($order['status'] === 'cancelled') {
                $response->error('Cannot process payment for cancelled order');
            }
            
            if (floatval($input['amount']) !== floatval($order['total_amount'])) {
                $response->error('Payment amount does not match order total');
            }
            
            // Generate transaction ID based on payment method
            $transaction_id = '';
            switch ($input['payment_method']) {
                case 'mpesa':
                    $transaction_id = 'MPESA_' . date('YmdHis') . '_' . uniqid();
                    break;
                case 'pesapal':
                    $transaction_id = 'PESAPAL_' . date('YmdHis') . '_' . uniqid();
                    break;
                case 'cash':
                    $transaction_id = 'CASH_' . date('YmdHis') . '_' . uniqid();
                    break;
                default:
                    $transaction_id = 'PAY_' . date('YmdHis') . '_' . uniqid();
            }
            
            // Create payment record
            $stmt = $db->prepare("
                INSERT INTO payments (
                    order_id, payment_method, amount, transaction_id, phone_number, status
                ) VALUES (?, ?, ?, ?, ?, 'pending')
            ");
            $stmt->execute([
                $input['order_id'],
                $input['payment_method'],
                $input['amount'],
                $transaction_id,
                $input['phone_number'] ?? null
            ]);
            
            $payment_id = $db->lastInsertId();
            
            // Simulate payment processing (in real app, this would call payment gateway)
            $payment_status = 'completed'; // Simulate successful payment
            
            // Update payment status
            $stmt = $db->prepare("UPDATE payments SET status = ? WHERE id = ?");
            $stmt->execute([$payment_status, $payment_id]);
            
            // Update order payment status
            $stmt = $db->prepare("UPDATE orders SET payment_status = ? WHERE id = ?");
            $stmt->execute([$payment_status === 'completed' ? 'paid' : 'failed', $input['order_id']]);
            
            $response->success([
                'payment_id' => $payment_id,
                'transaction_id' => $transaction_id,
                'status' => $payment_status
            ], 'Payment processed successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to process payment: ' . $e->getMessage());
        }
        break;
        
    case 'PUT':
        // Update payment status (for webhooks or admin actions)
        $user_data = $auth->protectRoute('admin', 'payments', 'edit');
        
        if (!$id) {
            $response->error('Payment ID is required', 400);
        }
        
        $required_fields = ['status'];
        $validation_result = $validation->validateRequired($input, $required_fields);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        try {
            // Get payment to update order status
            $stmt = $db->prepare("SELECT order_id FROM payments WHERE id = ?");
            $stmt->execute([$id]);
            $payment = $stmt->fetch();
            
            if (!$payment) {
                $response->notFound('Payment not found');
            }
            
            // Update payment status
            $stmt = $db->prepare("UPDATE payments SET status = ?, response_data = ? WHERE id = ?");
            $stmt->execute([
                $input['status'],
                json_encode($input['response_data'] ?? []),
                $id
            ]);
            
            // Update order payment status
            $order_payment_status = $input['status'] === 'completed' ? 'paid' : 'failed';
            $stmt = $db->prepare("UPDATE orders SET payment_status = ? WHERE id = ?");
            $stmt->execute([$order_payment_status, $payment['order_id']]);
            
            $response->success(null, 'Payment status updated successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to update payment: ' . $e->getMessage());
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}