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

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

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;
}

try {
    $conn->begin_transaction();
    
    // Handle customer phone - SIMPLIFIED
    $customer_id = null;
    $customer_phone = trim($input['customer_phone'] ?? '');
    
    if (!empty($customer_phone)) {
        // Insert customer
        $stmt = $conn->prepare("INSERT IGNORE INTO customers (name, phone, created_at) VALUES ('', ?, NOW())");
        $stmt->bind_param("s", $customer_phone);
        $stmt->execute();
        
        // Get customer ID
        $stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
        $stmt->bind_param("s", $customer_phone);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $customer_id = $row['id'];
        }
    }
    
    // Calculate totals
    $subtotal = 0;
    foreach ($input['items'] as $item) {
        $subtotal += $item['total'];
    }
    $discount_amount = $subtotal * ($input['discount'] / 100);
    $total_amount = $subtotal - $discount_amount;

    // Insert sale record
    $stmt = $conn->prepare("INSERT INTO sales (customer_id, customer_phone, total_amount, payment_method, discount, paid_amount) VALUES (?, ?, ?, ?, ?, ?)");
    $paid_amount = isset($input['paid_amount']) ? $input['paid_amount'] : 0;
    $stmt->bind_param("isdsdd", $customer_id, $customer_phone, $total_amount, $input['payment_method'], $input['discount'], $paid_amount);
    $stmt->execute();

    $sale_id = $conn->insert_id;
    
    // Insert sale items and update stock
    foreach ($input['items'] as $item) {
        // 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, $item['id'], $item['quantity'], $item['price'], $item['total']);
        $stmt->execute();
        
        // Update product stock
        $stmt = $conn->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
        $stmt->bind_param("ii", $item['quantity'], $item['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
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Error processing sale: ' . $e->getMessage()]);
}
?>
