<?php
// api.php
// This is a simple API endpoint to provide data for the UI
require_once 'db_connect.php';
require_once 'sms_api.php';

$action = $_GET['action'] ?? '';
$response = ['status' => 'error', 'message' => 'Invalid action'];

switch ($action) {
    case 'getBalance':
        $beemApi = new BeemApi(BEEM_API_KEY, BEEM_SECRET_KEY);
        $balanceData = $beemApi->getBalance();
        if (isset($balanceData['balance'])) {
            $response = ['status' => 'success', 'balance' => $balanceData['balance']];
        } else {
            $response['message'] = $balanceData['error'];
        }
        break;

    case 'getCategories':
        $sql = "SELECT sms_category_id, category_name FROM SMS_Categories ORDER BY category_name";
        $result = $conn->query($sql);
        $categories = [];
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
        $response = ['status' => 'success', 'data' => $categories];
        break;

    case 'getSmsLog':
        $sql = "SELECT sl.*, sc.category_name FROM SMS_Log sl LEFT JOIN SMS_Categories sc ON sl.sms_category_id = sc.sms_category_id WHERE 1=1";
        
        $params = [];
        $types = '';
        
        if (!empty($_GET['phone'])) {
            $sql .= " AND (sl.recipient_phone LIKE ?)";
            $params[] = '%' . $_GET['phone'] . '%';
            $types .= 's';
        }

        if (!empty($_GET['purpose'])) {
            $sql .= " AND sl.sms_category_id = ?";
            $params[] = $_GET['purpose'];
            $types .= 'i';
        }
        
        if (!empty($_GET['monthYear'])) {
            $sql .= " AND DATE_FORMAT(sl.sent_timestamp, '%Y-%m') = ?";
            $params[] = $_GET['monthYear'];
            $types .= 's';
        }
        
        $sql .= " ORDER BY sl.sent_timestamp DESC LIMIT 100"; // Limit to 100 for performance

        $stmt = $conn->prepare($sql);
        if ($types) {
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        $smsLog = [];
        while ($row = $result->fetch_assoc()) {
            $smsLog[] = $row;
        }
        $response = ['status' => 'success', 'data' => $smsLog];
        $stmt->close();
        break;
}

header('Content-Type: application/json');
echo json_encode($response);
$conn->close();
?>