<?php
/**
 * API: Manage Loyalty Points
 * Add, redeem, or adjust customer loyalty points
 */

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 POST data
$data = json_decode(file_get_contents('php://input'), true);

$action = isset($data['action']) ? $data['action'] : '';
$customerId = isset($data['customer_id']) ? intval($data['customer_id']) : 0;
$points = isset($data['points']) ? floatval($data['points']) : 0;
$notes = isset($data['notes']) ? mysqli_real_escape_string($con, $data['notes']) : '';
$userId = $_SESSION['uid'];

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

try {
    mysqli_begin_transaction($con);
    
    // Get current loyalty points
    $currentQuery = "SELECT LoyaltyPoints FROM tblcustomers WHERE ID = ? FOR UPDATE";
    $stmt = mysqli_prepare($con, $currentQuery);
    mysqli_stmt_bind_param($stmt, 'i', $customerId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) == 0) {
        mysqli_rollback($con);
        echo json_encode(['success' => false, 'message' => 'Customer not found']);
        exit();
    }
    
    $customer = mysqli_fetch_assoc($result);
    $currentPoints = floatval($customer['LoyaltyPoints']);
    
    // Determine transaction type and calculate new balance
    switch ($action) {
        case 'redeem':
            if ($points > $currentPoints) {
                mysqli_rollback($con);
                echo json_encode([
                    'success' => false, 
                    'message' => 'Insufficient points. Available: ' . $currentPoints
                ]);
                exit();
            }
            
            // Get minimum redemption points
            $minQuery = "SELECT SettingValue FROM tblsettings_loyalty WHERE SettingKey = 'min_redemption_points'";
            $minResult = mysqli_query($con, $minQuery);
            $minPoints = mysqli_fetch_assoc($minResult)['SettingValue'];
            
            if ($points < $minPoints) {
                mysqli_rollback($con);
                echo json_encode([
                    'success' => false, 
                    'message' => 'Minimum ' . $minPoints . ' points required for redemption'
                ]);
                exit();
            }
            
            $transactionType = 'REDEEMED';
            $newBalance = $currentPoints - $points;
            $pointsValue = -$points; // Negative for redemption
            
            // Update redeemed total
            $updateQuery = "UPDATE tblcustomers 
                          SET LoyaltyPoints = ?, 
                              TotalPointsRedeemed = TotalPointsRedeemed + ?
                          WHERE ID = ?";
            break;
            
        case 'adjust':
            $transactionType = 'ADJUSTED';
            if ($points > 0) {
                $newBalance = $currentPoints + $points;
                $pointsValue = $points;
                $updateQuery = "UPDATE tblcustomers 
                              SET LoyaltyPoints = ?, 
                                  TotalPointsEarned = TotalPointsEarned + ?
                              WHERE ID = ?";
            } else {
                $newBalance = $currentPoints + $points; // points is negative
                $pointsValue = $points;
                $updateQuery = "UPDATE tblcustomers 
                              SET LoyaltyPoints = ?
                              WHERE ID = ?";
            }
            break;
            
        default:
            mysqli_rollback($con);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            exit();
    }
    
    // Insert transaction record
    $transQuery = "INSERT INTO tblcustomer_loyalty_points 
                   (CustomerID, TransactionType, Points, CurrentBalance, CreatedBy, Notes, Reference)
                   VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($con, $transQuery);
    $reference = 'MANUAL-' . date('YmdHis');
    mysqli_stmt_bind_param($stmt, 'isddiss', $customerId, $transactionType, $pointsValue, 
                          $newBalance, $userId, $notes, $reference);
    
    if (!mysqli_stmt_execute($stmt)) {
        mysqli_rollback($con);
        echo json_encode(['success' => false, 'message' => 'Failed to record transaction']);
        exit();
    }
    
    // Update customer points
    $stmt = mysqli_prepare($con, $updateQuery);
    if ($action == 'adjust' && $points < 0) {
        mysqli_stmt_bind_param($stmt, 'di', $newBalance, $customerId);
    } else {
        mysqli_stmt_bind_param($stmt, 'ddi', $newBalance, abs($pointsValue), $customerId);
    }
    
    if (!mysqli_stmt_execute($stmt)) {
        mysqli_rollback($con);
        echo json_encode(['success' => false, 'message' => 'Failed to update customer points']);
        exit();
    }
    
    mysqli_commit($con);
    
    echo json_encode([
        'success' => true,
        'message' => ucfirst($action) . ' successful',
        'previousBalance' => $currentPoints,
        'pointsChanged' => $pointsValue,
        'newBalance' => $newBalance,
        'reference' => $reference
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($con);
    echo json_encode([
        'success' => false,
        'message' => 'Error managing loyalty points: ' . $e->getMessage()
    ]);
}
?>
