<?php
/**
 * ============================================================================
 * farm/add-transaction.php - Add Financial Transaction
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

if (getUserType() !== 'farmer') {
    redirect('/dashboard/', 'Only farmers can access farm management', 'error');
}

$pageTitle = 'Add Transaction';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get user's enterprises
$sql = "SELECT e.*, f.farm_name 
        FROM enterprises e
        JOIN farms f ON e.farm_id = f.id
        WHERE f.user_id = ?
        ORDER BY e.enterprise_name, e.enterprise_type";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$enterprises = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
if (isPost()) {
    $transactionClass = new \App\Transaction($db);
    
    $data = [
        'transaction_type' => $_POST['transaction_type'],
        'enterprise_id' => $_POST['enterprise_id'] ?: null,
        'category' => $_POST['category'],
        'amount' => $_POST['amount'],
        'description' => $_POST['description'],
        'transaction_date' => $_POST['transaction_date'] ?: date('Y-m-d'),
        'receipt_url' => null
    ];
    
    // Handle file upload if present
    if (!empty($_FILES['receipt']['name'])) {
        $uploadResult = uploadFile($_FILES['receipt'], 'receipts');
        if ($uploadResult['success']) {
            $data['receipt_url'] = $uploadResult['file_path'];
        }
    }
    
    $result = $transactionClass->create($userId, $data);
    
    if ($result['success']) {
        redirect('/farm/transactions.php', $result['message'], 'success');
    } else {
        setFlashMessage($result['message'], 'error');
    }
}

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h4 class="mb-0">
                        <i class="bi bi-plus-circle text-success"></i> Add Transaction
                    </h4>
                </div>
                <div class="card-body p-4">
                    <form method="POST" enctype="multipart/form-data">
                        <!-- Transaction Type -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">Transaction Type <span class="text-danger">*</span></label>
                            <div class="row">
                                <div class="col-6">
                                    <div class="form-check form-check-lg">
                                        <input class="form-check-input" type="radio" name="transaction_type" 
                                               id="typeIncome" value="income" required>
                                        <label class="form-check-label" for="typeIncome">
                                            <i class="bi bi-arrow-up-circle text-success"></i> Income
                                        </label>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-check form-check-lg">
                                        <input class="form-check-input" type="radio" name="transaction_type" 
                                               id="typeExpense" value="expense" required>
                                        <label class="form-check-label" for="typeExpense">
                                            <i class="bi bi-arrow-down-circle text-danger"></i> Expense
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Category -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Category <span class="text-danger">*</span></label>
                            <select class="form-select" name="category" id="categorySelect" required>
                                <option value="">Select category...</option>
                                <!-- Income categories -->
                                <optgroup label="Income Categories" id="incomeCategories">
                                    <option value="Product Sales">Product Sales</option>
                                    <option value="Livestock Sales">Livestock Sales</option>
                                    <option value="Produce Sales">Produce Sales</option>
                                    <option value="Grant/Subsidy">Grant/Subsidy</option>
                                    <option value="Service Income">Service Income</option>
                                    <option value="Other Income">Other Income</option>
                                </optgroup>
                                <!-- Expense categories -->
                                <optgroup label="Expense Categories" id="expenseCategories">
                                    <option value="Seeds/Seedlings">Seeds/Seedlings</option>
                                    <option value="Fertilizers">Fertilizers</option>
                                    <option value="Pesticides">Pesticides</option>
                                    <option value="Feed">Animal Feed</option>
                                    <option value="Veterinary">Veterinary Services</option>
                                    <option value="Labor">Labor/Wages</option>
                                    <option value="Equipment">Equipment/Tools</option>
                                    <option value="Fuel">Fuel/Transport</option>
                                    <option value="Utilities">Utilities (Water, Electric)</option>
                                    <option value="Rent">Land Rent</option>
                                    <option value="Maintenance">Repairs & Maintenance</option>
                                    <option value="Other Expense">Other Expense</option>
                                </optgroup>
                            </select>
                        </div>

                        <!-- Enterprise (Optional) -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Enterprise (Optional)</label>
                            <select class="form-select" name="enterprise_id">
                                <option value="">General (not linked to enterprise)</option>
                                <?php foreach ($enterprises as $ent): ?>
                                    <option value="<?php echo $ent['id']; ?>">
                                        <?php echo htmlspecialchars($ent['enterprise_name'] ?: ucfirst(str_replace('_', ' ', $ent['enterprise_type']))); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Link this transaction to a specific enterprise</small>
                        </div>

                        <!-- Amount -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Amount (UGX) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control form-control-lg" name="amount" 
                                   min="0" step="0.01" placeholder="0.00" required>
                        </div>

                        <!-- Date -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Transaction Date</label>
                            <input type="date" class="form-control" name="transaction_date" 
                                   value="<?php echo date('Y-m-d'); ?>">
                        </div>

                        <!-- Description -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Description <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="description" rows="3" 
                                      placeholder="Brief description of the transaction..." required></textarea>
                        </div>

                        <!-- Receipt Upload (Optional) -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">Receipt/Document (Optional)</label>
                            <input type="file" class="form-control" name="receipt" 
                                   accept="image/*,.pdf">
                            <small class="text-muted">Upload a receipt or invoice (max 5MB)</small>
                        </div>

                        <!-- Buttons -->
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="<?php echo APP_URL; ?>/farm/transactions.php" class="btn btn-outline-secondary">
                                <i class="bi bi-x-circle"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-success">
                                <i class="bi bi-check-circle"></i> Add Transaction
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initially disable all category options
    $('#incomeCategories option').prop('disabled', true);
    $('#expenseCategories option').prop('disabled', true);
    
    // Show/hide categories based on transaction type
    $('input[name="transaction_type"]').on('change', function() {
        const type = $(this).val();
        $('#categorySelect').val('');
        
        if (type === 'income') {
            // Enable income options, disable expense options
            $('#incomeCategories option').prop('disabled', false);
            $('#expenseCategories option').prop('disabled', true);
        } else {
            // Enable expense options, disable income options
            $('#incomeCategories option').prop('disabled', true);
            $('#expenseCategories option').prop('disabled', false);
        }
    });
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>