<?php
/**
 * API: Get Customer Loyalty Points
 * Returns customer's loyalty points balance and transaction history
 */

header('Content-Type: application/json');
session_start();
include_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get customer ID from request
$customerId = isset($_GET['customer_id']) ? intval($_GET['customer_id']) : 0;

if ($customerId == 0) {
    echo json_encode(['success' => false, 'message' => 'Customer ID required']);
    exit();
}

try {
    // Get customer loyalty points summary
    $customerQuery = "SELECT ID, CustomerCode, CustomerName, LoyaltyPoints, 
                      TotalPointsEarned, TotalPointsRedeemed 
                      FROM tblcustomers WHERE ID = ?";
    $stmt = mysqli_prepare($con, $customerQuery);
    mysqli_stmt_bind_param($stmt, 'i', $customerId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) == 0) {
        echo json_encode(['success' => false, 'message' => 'Customer not found']);
        exit();
    }
    
    $customer = mysqli_fetch_assoc($result);
    
    // Get recent transactions (last 50)
    $transactionsQuery = "SELECT 
                          lp.ID,
                          lp.TransactionDate,
                          lp.TransactionType,
                          lp.Points,
                          lp.SaleID,
                          lp.Reference,
                          lp.Notes,
                          lp.CurrentBalance,
                          s.InvoiceNumber
                          FROM tblcustomer_loyalty_points lp
                          LEFT JOIN tblsales s ON lp.SaleID = s.ID
                          WHERE lp.CustomerID = ?
                          ORDER BY lp.TransactionDate DESC, lp.ID DESC
                          LIMIT 50";
    
    $stmt = mysqli_prepare($con, $transactionsQuery);
    mysqli_stmt_bind_param($stmt, 'i', $customerId);
    mysqli_stmt_execute($stmt);
    $transResult = mysqli_stmt_get_result($stmt);
    
    $transactions = [];
    while ($row = mysqli_fetch_assoc($transResult)) {
        $transactions[] = [
            'id' => $row['ID'],
            'date' => $row['TransactionDate'],
            'type' => $row['TransactionType'],
            'points' => floatval($row['Points']),
            'saleId' => $row['SaleID'],
            'invoiceNumber' => $row['InvoiceNumber'],
            'reference' => $row['Reference'],
            'notes' => $row['Notes'],
            'balance' => floatval($row['CurrentBalance'])
        ];
    }
    
    // Get loyalty settings
    $settingsQuery = "SELECT SettingKey, SettingValue FROM tblsettings_loyalty";
    $settingsResult = mysqli_query($con, $settingsQuery);
    $settings = [];
    while ($row = mysqli_fetch_assoc($settingsResult)) {
        $settings[$row['SettingKey']] = $row['SettingValue'];
    }
    
    echo json_encode([
        'success' => true,
        'customer' => [
            'id' => $customer['ID'],
            'code' => $customer['CustomerCode'],
            'name' => $customer['CustomerName'],
            'currentPoints' => floatval($customer['LoyaltyPoints']),
            'totalEarned' => floatval($customer['TotalPointsEarned']),
            'totalRedeemed' => floatval($customer['TotalPointsRedeemed'])
        ],
        'transactions' => $transactions,
        'settings' => $settings
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching loyalty points: ' . $e->getMessage()
    ]);
}
?>
