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

// Ensure auth
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

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

// Ensure tables exist
$conn->query("CREATE TABLE IF NOT EXISTS sales_officers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, is_active TINYINT(1) DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
$conn->query("CREATE TABLE IF NOT EXISTS sales_commissions (id INT AUTO_INCREMENT PRIMARY KEY, sale_id INT NOT NULL, sales_officer_id INT NOT NULL, commission_amount DECIMAL(10,2) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (sale_id) REFERENCES sales(id) ON DELETE CASCADE, FOREIGN KEY (sales_officer_id) REFERENCES sales_officers(id) ON DELETE CASCADE)");

if ($_GET['action'] === 'verify') {
    // Check if test officer exists
    $result = $conn->query("SELECT id FROM sales_officers WHERE name = 'test' AND is_active = 1 LIMIT 1");
    
    if ($result && $result->num_rows > 0) {
        $officer = $result->fetch_assoc();
        echo json_encode([
            'status' => 'ok',
            'message' => 'Test officer exists and is active',
            'officer_id' => $officer['id']
        ]);
    } else {
        // Create test officer
        $conn->query("INSERT IGNORE INTO sales_officers (name, is_active) VALUES ('test', 1)");
        $officer_id = $conn->insert_id ?: $conn->query("SELECT id FROM sales_officers WHERE name = 'test'")->fetch_assoc()['id'];
        
        echo json_encode([
            'status' => 'created',
            'message' => 'Test officer created',
            'officer_id' => $officer_id
        ]);
    }
} 
elseif ($_GET['action'] === 'check_commissions') {
    // Check December 2025 commissions
    $result = $conn->query("SELECT COUNT(*) as count FROM sales_commissions WHERE DATE(created_at) >= '2025-12-01' AND DATE(created_at) <= '2025-12-31'");
    $row = $result->fetch_assoc();
    
    echo json_encode([
        'december_commissions' => $row['count'],
        'message' => $row['count'] > 0 ? 'Commissions found for December' : 'No commissions found for December yet'
    ]);
}
elseif ($_GET['action'] === 'check_sales') {
    // Check December 2025 sales
    $result = $conn->query("SELECT COUNT(*) as count FROM sales WHERE DATE(sale_date) >= '2025-12-01' AND DATE(sale_date) <= '2025-12-31'");
    $row = $result->fetch_assoc();
    
    echo json_encode([
        'december_sales' => $row['count'],
        'message' => $row['count'] > 0 ? 'Sales found for December' : 'No sales found for December yet'
    ]);
}
elseif ($_GET['action'] === 'debug_full') {
    // Full diagnostic
    $officers_result = $conn->query("SELECT COUNT(*) as count FROM sales_officers");
    $officers_count = $officers_result->fetch_assoc()['count'];
    
    $sales_result = $conn->query("SELECT COUNT(*) as count FROM sales WHERE DATE(sale_date) >= '2025-12-01' AND DATE(sale_date) <= '2025-12-31'");
    $sales_count = $sales_result->fetch_assoc()['count'];
    
    $commissions_result = $conn->query("SELECT COUNT(*) as count FROM sales_commissions WHERE DATE(created_at) >= '2025-12-01' AND DATE(created_at) <= '2025-12-31'");
    $commissions_count = $commissions_result->fetch_assoc()['count'];
    
    // Get last commission
    $last_commission = $conn->query("SELECT sc.*, so.name, s.total_amount FROM sales_commissions sc LEFT JOIN sales_officers so ON sc.sales_officer_id = so.id LEFT JOIN sales s ON sc.sale_id = s.id ORDER BY sc.id DESC LIMIT 1");
    $last_comm = $last_commission ? $last_commission->fetch_assoc() : null;
    
    echo json_encode([
        'officers_count' => $officers_count,
        'december_sales_count' => $sales_count,
        'december_commissions_count' => $commissions_count,
        'last_commission' => $last_comm
    ]);
}
else {
    echo json_encode(['error' => 'Unknown action']);
}
?>
