<?php
/**
 * SMS API Routes
 * 
 * Handles SMS configuration, sending, and 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 SMS log
            $stmt = $db->prepare("SELECT * FROM sms_logs WHERE id = ?");
            $stmt->execute([$id]);
            $sms = $stmt->fetch();
            
            if (!$sms) {
                $response->notFound('SMS log not found');
            }
            
            $response->success($sms);
            
        } else {
            // Get all SMS logs 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;
            $type = $_GET['type'] ?? null;
            $date_from = $_GET['date_from'] ?? null;
            $date_to = $_GET['date_to'] ?? null;
            
            $where_conditions = [];
            $params = [];
            
            if ($status) {
                $where_conditions[] = "status = ?";
                $params[] = $status;
            }
            
            if ($type) {
                $where_conditions[] = "message_type = ?";
                $params[] = $type;
            }
            
            if ($date_from) {
                $where_conditions[] = "DATE(created_at) >= ?";
                $params[] = $date_from;
            }
            
            if ($date_to) {
                $where_conditions[] = "DATE(created_at) <= ?";
                $params[] = $date_to;
            }
            
            $where_clause = $where_conditions ? "WHERE " . implode(' AND ', $where_conditions) : "";
            
            // Get SMS logs
            $stmt = $db->prepare("
                SELECT * FROM sms_logs 
                $where_clause 
                ORDER BY created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);
            $sms_logs = $stmt->fetchAll();
            
            // Get total count
            $stmt = $db->prepare("SELECT COUNT(*) as total FROM sms_logs $where_clause");
            $count_params = array_slice($params, 0, count($params) - 2);
            $stmt->execute($count_params);
            $total = $stmt->fetch()['total'];
            
            $response->success([
                'sms_logs' => $sms_logs,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $total,
                    'pages' => ceil($total / $limit)
                ]
            ]);
        }
        break;
        
    case 'POST':
        // Send SMS
        $user_data = $auth->protectRoute('admin', 'sms', 'create');
        
        $required_fields = ['recipient_phone', 'message'];
        $validation_result = $validation->validateRequired($input, $required_fields);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        // Validate phone number
        $phone_result = $validation->validatePhone($input['recipient_phone']);
        if (!$phone_result['valid']) {
            $response->validationError(['recipient_phone' => $phone_result['message']]);
        }
        
        try {
            // Get SMS settings
            $stmt = $db->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'sms_enabled'");
            $stmt->execute();
            $sms_enabled = $stmt->fetch()['setting_value'] === 'true';
            
            if (!$sms_enabled) {
                $response->error('SMS notifications are currently disabled');
            }
            
            // Create SMS log
            $stmt = $db->prepare("
                INSERT INTO sms_logs (recipient_phone, message, message_type, status) 
                VALUES (?, ?, ?, 'pending')
            ");
            $stmt->execute([
                $phone_result['cleaned'],
                $validation->sanitize($input['message']),
                $input['message_type'] ?? 'promotional'
            ]);
            
            $sms_id = $db->lastInsertId();
            
            // Simulate SMS sending (in real app, this would call Africa's Talking API)
            $sms_status = 'sent'; // Simulate successful sending
            $response_data = ['simulated' => true, 'message_id' => 'SIM_' . uniqid()];
            
            // Update SMS log
            $stmt = $db->prepare("
                UPDATE sms_logs 
                SET status = ?, response_data = ?, sent_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$sms_status, json_encode($response_data), $sms_id]);
            
            $response->success([
                'sms_id' => $sms_id,
                'status' => $sms_status,
                'message_id' => $response_data['message_id']
            ], 'SMS sent successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to send SMS: ' . $e->getMessage());
        }
        break;
        
    case 'PUT':
        // Update SMS configuration
        $user_data = $auth->protectRoute('admin', 'sms', 'edit');
        
        if ($action === 'settings') {
            // Update SMS settings
            $valid_settings = [
                'africas_talking_api_key',
                'africas_talking_username',
                'sms_enabled',
                'payment_notifications',
                'order_updates',
                'appointment_reminders',
                'promotional_sms'
            ];
            
            try {
                foreach ($input as $key => $value) {
                    if (in_array($key, $valid_settings)) {
                        $stmt = $db->prepare("
                            INSERT INTO system_settings (setting_key, setting_value, setting_type, updated_by) 
                            VALUES (?, ?, 'string', ?) 
                            ON DUPLICATE KEY UPDATE 
                            setting_value = VALUES(setting_value), 
                            updated_by = VALUES(updated_by), 
                            updated_at = NOW()
                        ");
                        
                        $setting_type = is_bool($value) ? 'boolean' : 'string';
                        $setting_value = is_bool($value) ? ($value ? 'true' : 'false') : $value;
                        
                        $stmt->execute([$key, $setting_value, $user_data['user_id']]);
                    }
                }
                
                $response->success(null, 'SMS settings updated successfully');
                
            } catch (Exception $e) {
                $response->error('Failed to update SMS settings: ' . $e->getMessage());
            }
            
        } else {
            $response->error('Invalid action specified', 400);
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}