<?php
session_start();
require_once '../config.php';
require_once '../app/classes/BalanceHistory.php';
require_once '../app/classes/StoreManager.php';

use App\classes\BalanceHistory;

header('Content-Type: application/json');

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

$userId = $_SESSION['user_id'];

// Verify user is a store owner
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    echo json_encode(['success' => false, 'message' => 'You are not a store owner']);
    exit;
}

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Get and validate input
$agentId = isset($_POST['agent_id']) ? intval($_POST['agent_id']) : 0;
$amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
$action = isset($_POST['action']) ? trim($_POST['action']) : '';
$note = isset($_POST['note']) ? trim($_POST['note']) : '';

if ($agentId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid agent ID']);
    exit;
}

if ($amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Amount must be greater than zero']);
    exit;
}

if ($amount > 50000) {
    echo json_encode(['success' => false, 'message' => 'Amount cannot exceed GH₵ 50,000']);
    exit;
}

if (!in_array($action, ['credit', 'debit'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

// Verify agent belongs to this store
$stmt = $conn->prepare("SELECT id, username, balance, store_id FROM agents WHERE id = ? AND store_id = ?");
$stmt->bind_param("ii", $agentId, $store['id']);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $stmt->close();
    echo json_encode(['success' => false, 'message' => 'Agent not found or does not belong to your store']);
    exit;
}

$agent = $result->fetch_assoc();
$stmt->close();

// Start transaction
$conn->begin_transaction();

try {
    $currentBalance = floatval($agent['balance']);
    
    if ($action === 'debit') {
        // Check if debit would result in negative balance
        if ($currentBalance < $amount) {
            throw new Exception('Insufficient balance. Cannot debit GH₵ ' . number_format($amount, 2) . '. Current balance: GH₵ ' . number_format($currentBalance, 2));
        }
        $newBalance = round($currentBalance - $amount, 2);
        $transactionAmount = -1 * $amount; // Negative for debit
    } else {
        // Credit
        $newBalance = round($currentBalance + $amount, 2);
        $transactionAmount = $amount; // Positive for credit
    }
    
    // Update agent balance
    $stmt = $conn->prepare("UPDATE agents SET balance = ? WHERE id = ?");
    $stmt->bind_param("di", $newBalance, $agentId);
    if (!$stmt->execute()) {
        throw new Exception('Failed to update agent balance');
    }
    $stmt->close();
    
    // Log balance history
    $historyNote = 'Store owner ' . ($action === 'credit' ? 'credited' : 'debited') . ' balance';
    if ($note) {
        $historyNote .= ': ' . $note;
    }
    
    if (!BalanceHistory::log($conn, $agentId, $transactionAmount, $action === 'credit' ? 'payment' : 'debit', null, $historyNote)) {
        error_log("Failed to log balance history for agent $agentId");
    }
    
    // Record in orders_payments for tracking
    $stmt = $conn->prepare("INSERT INTO orders_payments (user_id, total_amount, payment_method, payment_status, created_at) VALUES (?, ?, 'store_owner_manual', 'completed', NOW())");
    $stmt->bind_param("id", $agentId, $transactionAmount);
    $stmt->execute();
    $stmt->close();
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Balance ' . ($action === 'credit' ? 'credited' : 'debited') . ' successfully',
        'new_balance' => $newBalance,
        'previous_balance' => $currentBalance,
        'amount' => $amount
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}






