<?php
session_start();
require_once 'config.php';

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

// Check auth
if (!isset($_SESSION['user_id'])) {
    die(json_encode(['error' => 'Not authenticated']));
}

// Create test sale with commission
try {
    // Ensure tables exist
    $conn->query("CREATE TABLE IF NOT EXISTS sales_officers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        is_active BOOLEAN DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    
    $conn->query("CREATE TABLE IF NOT EXISTS sales_commissions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        sales_officer_id INT,
        sale_id INT,
        commission_amount DECIMAL(10, 2),
        commission_rate DECIMAL(5, 3),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (sales_officer_id) REFERENCES sales_officers(id),
        FOREIGN KEY (sale_id) REFERENCES sales(id)
    )");
    
    // Get or create test officer
    $officer_result = $conn->query("SELECT id FROM sales_officers WHERE name = 'test' LIMIT 1");
    if ($officer_result && $officer_result->num_rows > 0) {
        $officer = $officer_result->fetch_assoc();
        $officer_id = $officer['id'];
    } else {
        $conn->query("INSERT INTO sales_officers (name, is_active) VALUES ('test', 1)");
        $officer_id = $conn->insert_id;
    }
    
    // Create test sale
    $customer_id = 1;
    $total_amount = 1000;
    $paid_amount = 1000;
    $user_id = $_SESSION['user_id'];
    $description = "Test sale for commission testing";
    
    $stmt = $conn->prepare("INSERT INTO sales (customer_id, total_amount, paid_amount, user_id, description, sale_date) 
                            VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param('idids', $customer_id, $total_amount, $paid_amount, $user_id, $description);
    $stmt->execute();
    $sale_id = $conn->insert_id;
    
    // Create commission record
    $commission_rate = 0.01;
    $commission_amount = round($total_amount * $commission_rate, 2);
    
    $comm_stmt = $conn->prepare("INSERT INTO sales_commissions (sales_officer_id, sale_id, commission_amount, commission_rate) 
                                 VALUES (?, ?, ?, ?)");
    $comm_stmt->bind_param('iidd', $officer_id, $sale_id, $commission_amount, $commission_rate);
    $comm_stmt->execute();
    
    // Verify
    $verify = $conn->query("SELECT COUNT(*) as total FROM sales_commissions WHERE sales_officer_id = $officer_id");
    $count = $verify->fetch_assoc()['total'];
    
    echo json_encode([
        'success' => true,
        'message' => "Test sale created",
        'sale_id' => $sale_id,
        'officer_id' => $officer_id,
        'commission_amount' => $commission_amount,
        'total_commissions_for_officer' => $count
    ]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
