<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';

// Ensure sales officer 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)");

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

// DEBUG: Direct customer insert test
if (isset($_GET['debug_customer_insert'])) {
    $test_phone = '9999999999';
    $test_name = 'Customer 9999';
    $stmt = $conn->prepare("INSERT IGNORE INTO customers (name, phone, created_at) VALUES (?, ?, NOW())");
    $stmt->bind_param("ss", $test_name, $test_phone);
    if ($stmt->execute()) {
        echo "Customer insert success.\n";
    } else {
        echo "Customer insert failed: " . $stmt->error . "\n";
    }
    $stmt->close();
    exit;
}

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

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
    exit;
}

$sales_officer_id = isset($input['sales_officer_id']) && $input['sales_officer_id'] !== '' ? intval($input['sales_officer_id']) : null;
$commission_rate = 0.01; // 1% commission

try {
    $conn->begin_transaction();
    
    // TOP-LEVEL LOG: Record every sale request
    file_put_contents(__DIR__ . '/customer_insert_log.txt', date('Y-m-d H:i:s') . " - Sale request received\n", FILE_APPEND);
    
    // DEBUG: Log full sale data received
    file_put_contents(__DIR__ . '/sale_data_log.txt', date('Y-m-d H:i:s') . "\n" . print_r($input, true) . "\n", FILE_APPEND);
    
    // DEBUG: Log raw POST data for sale requests
    file_put_contents(__DIR__ . '/sale_raw_post.txt', file_get_contents('php://input'));
    
    // Always create or update customer record for every sale with a phone number
    $customer_id = null;
    $customer_phone = $input['customer_phone'] ?? null;
    
    // Also try getting phone from $_POST if JSON fails
    if (!$customer_phone && isset($_POST['customer_phone'])) {
        $customer_phone = $_POST['customer_phone'];
    }
    
    // LOGGING: Record every phone number received and customer insert attempt
    file_put_contents(__DIR__ . '/customer_insert_log.txt', date('Y-m-d H:i:s') . " - Received phone: " . ($customer_phone ?? 'NULL') . "\n", FILE_APPEND);
    if ($customer_phone && trim($customer_phone) !== '') {
        $customer_phone = trim($customer_phone);
        file_put_contents(__DIR__ . '/customer_insert_log.txt', date('Y-m-d H:i:s') . " - Attempting customer insert for: " . $customer_phone . "\n", FILE_APPEND);
    }
    if ($customer_phone && trim($customer_phone) !== '') {
        $customer_phone = trim($customer_phone);
        file_put_contents(__DIR__ . '/customer_insert_log.txt', date('Y-m-d H:i:s') . " - Attempting customer insert for: " . $customer_phone . "\n", FILE_APPEND);
        try {
            // Always insert customer with blank name if phone is provided
            $blank_name = '';
            $stmt = $conn->prepare("INSERT IGNORE INTO customers (name, phone, created_at) VALUES (?, ?, NOW())");
            $stmt->bind_param("ss", $blank_name, $customer_phone);
            if (!$stmt->execute()) {
                $customer_creation_error = $stmt->error;
                error_log('Customer creation DB error: ' . $stmt->error);
            }
            // Get customer ID (new or existing)
            $stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
            $stmt->bind_param("s", $customer_phone);
            $stmt->execute();
            $existing_customer = $stmt->get_result()->fetch_assoc();
            if ($existing_customer) {
                $customer_id = $existing_customer['id'];
            }
        } catch (Exception $e) {
            $customer_creation_error = $e->getMessage();
            error_log('Customer creation exception: ' . $e->getMessage());
        }
    }
    
    // Check if this sale is from a held order
    $held_order_id = isset($input['held_order_id']) ? intval($input['held_order_id']) : null;
    
    // Calculate totals
    $subtotal = 0;
    foreach ($input['items'] as $item) {
        $subtotal += $item['total'];
    }
    // Support discount as percentage (e.g., '10%') or rupees (e.g., '100')
    $discount_raw = $input['discount'];
    $discount_amount = 0;
    if (is_string($discount_raw) && strpos($discount_raw, '%') !== false) {
        // Percentage discount
        $percent = floatval(str_replace('%', '', $discount_raw));
        $discount_amount = $subtotal * ($percent / 100);
    } else {
        // Rupee discount (number or string)
        $discount_amount = floatval($discount_raw);
    }
    $total_amount = $subtotal - $discount_amount;

    // Voucher logic: store voucher value, secondary payment method, and secondary amount if payment method is voucher
    if ($input['payment_method'] === 'voucher') {
        $voucher_value = isset($input['voucher_value']) ? $input['voucher_value'] : 0;
        $secondary_payment_method = isset($input['secondary_payment_method']) ? $input['secondary_payment_method'] : null;
        $secondary_amount = isset($input['secondary_amount']) ? $input['secondary_amount'] : 0;
        $stmt = $conn->prepare("INSERT INTO sales (customer_id, held_order_id, customer_phone, total_amount, payment_method, discount, paid_amount, voucher_amount, secondary_payment_method, secondary_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $paid_amount = isset($input['paid_amount']) ? $input['paid_amount'] : 0;
        $stmt->bind_param("iisdsdddsd", $customer_id, $held_order_id, $customer_phone, $total_amount, $input['payment_method'], $input['discount'], $paid_amount, $voucher_value, $secondary_payment_method, $secondary_amount);
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("INSERT INTO sales (customer_id, held_order_id, customer_phone, total_amount, payment_method, discount, paid_amount) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $paid_amount = isset($input['paid_amount']) ? $input['paid_amount'] : 0;
        $stmt->bind_param("iisdsdd", $customer_id, $held_order_id, $customer_phone, $total_amount, $input['payment_method'], $input['discount'], $paid_amount);
        $stmt->execute();
    }

    $sale_id = $conn->insert_id;

    // Record commission for selected sales officer
    file_put_contents(__DIR__ . '/commission_log.txt', date('Y-m-d H:i:s') . " - Sales Officer ID: " . ($sales_officer_id ?? 'NULL') . ", Sale ID: " . $sale_id . ", Total: " . $total_amount . "\n", FILE_APPEND);
    
    if ($sales_officer_id) {
        $commission_amount = round($total_amount * $commission_rate, 2);
        $stmt = $conn->prepare("INSERT INTO sales_commissions (sale_id, sales_officer_id, commission_amount) VALUES (?, ?, ?)");
        $stmt->bind_param("iid", $sale_id, $sales_officer_id, $commission_amount);
        if ($stmt->execute()) {
            file_put_contents(__DIR__ . '/commission_log.txt', date('Y-m-d H:i:s') . " - Commission inserted: Rs. " . $commission_amount . " for officer " . $sales_officer_id . "\n", FILE_APPEND);
        } else {
            file_put_contents(__DIR__ . '/commission_log.txt', date('Y-m-d H:i:s') . " - Commission insertion FAILED: " . $stmt->error . "\n", FILE_APPEND);
        }
    } else {
        file_put_contents(__DIR__ . '/commission_log.txt', date('Y-m-d H:i:s') . " - No sales officer selected\n", FILE_APPEND);
    }
    
    // Insert sale items and update stock
    foreach ($input['items'] as $item) {
        $product_id = $item['id'];
        // If product_id is not numeric, treat as custom product and insert into products table
        if (!is_numeric($product_id)) {
            $custom_name = $conn->real_escape_string($item['name']);
            $custom_price = floatval($item['price']);
            // Insert custom product (category 'Custom', stock 0)
            $conn->query("INSERT INTO products (name, category, price, stock) VALUES ('{$custom_name}', 'Custom', {$custom_price}, 0)");
            $product_id = $conn->insert_id;
        }
        // Insert sale item
        $stmt = $conn->prepare("INSERT INTO sale_items (sale_id, product_id, quantity, unit_price, total_price) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("iiidd", $sale_id, $product_id, $item['quantity'], $item['price'], $item['total']);
        $stmt->execute();
        // Only update stock for real products
        if (is_numeric($item['id'])) {
            $stmt = $conn->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
            $stmt->bind_param("ii", $item['quantity'], $item['id']);
            $stmt->execute();
        }
    }
    
    // If this sale was from a held order, mark the held order as completed
    if ($held_order_id) {
        $stmt = $conn->prepare("UPDATE held_orders SET status = 'completed', updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("i", $held_order_id);
        $stmt->execute();
    }
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Sale completed successfully',
        'sale_id' => $sale_id,
        'total' => $total_amount,
        'customer_phone_received' => $customer_phone,
        'customer_id_used' => $customer_id,
        'customer_creation_error' => isset($customer_creation_error) ? $customer_creation_error : null,
        'held_order_processed' => $held_order_id ? true : false,
        'raw_input_data' => $input
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error processing sale: ' . $e->getMessage()]);
}
?>
