<?php
session_start();
include '../config/db.php';

// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Ensure session username is set
if (!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'User session is not set.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents("php://input"); 
    $cartData = json_decode($input, true);

    if ($cartData === null) {
        echo json_encode(['success' => false, 'message' => 'Invalid cart data format.']);
        exit;
    }

    // Retrieve data from session and request
    $username = $_SESSION['username'];
    $receipt = uniqid(); 
    $totalDiscount = isset($cartData['discount']) ? floatval($cartData['discount']) : 0; // Total discount applied
    $paymentMethod1 = $cartData['paymentMethod1'] ?? 'Cash';
    $paymentAmount1 = isset($cartData['paymentAmount1']) ? floatval($cartData['paymentAmount1']) : 0.00;
    
    $paymentMethod2 = $cartData['paymentMethod2'] ?? '';
    $paymentAmount2 = isset($cartData['paymentAmount2']) ? floatval($cartData['paymentAmount2']) : 0.00;

    $customer = $cartData['customer'] ?? null;
    $owingAmount = floatval($cartData['owingAmount'] ?? 0);  // Ensure owingAmount is initialized
    $owingType = $cartData['owingType'] ?? '';

    
    try {
        $pdo->beginTransaction();
        $totalProfit = 0;
        $totalAmount = 0;

        // Store the IDs of the inserted sales
        $saleIds = [];
        $salesData = [];
        $activityDetails = [];

        // Calculate the total sales amount and adjust for payments
        $totalCartAmount = 0;
        foreach ($cartData['cart'] as $item) {
            $totalCartAmount += $item['totalPrice'];
        }

        // Distribute payment amounts across sales
        $paymentAmount1PerSale = ($totalCartAmount > 0) ? ($paymentAmount1 / $totalCartAmount) : 0;
        $paymentAmount2PerSale = ($totalCartAmount > 0) ? ($paymentAmount2 / $totalCartAmount) : 0;

        // Process each cart item and insert sale records
        foreach ($cartData['cart'] as $item) {
            $drugId = $item['id'];
            $quantity = $item['quantity'];
            $saleType = $item['saleType'];
            $totalPrice = $item['totalPrice'];

            // Fetch drug details
            $query = "SELECT quantity, volume_size, cost_price FROM drugs WHERE id = :id";
            $stmt = $pdo->prepare($query);
            $stmt->execute(['id' => $drugId]);
            $drug = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$drug) {
                throw new Exception("Drug not found.");
            }

            // Calculate the quantity to deduct
            $deductQuantity = ($saleType === 'volume') ? $quantity * $drug['volume_size'] : $quantity;

            // Check stock availability
            if ($drug['quantity'] < $deductQuantity) {
                throw new Exception("Insufficient stock for {$item['drugName']}.");
            }

            // Calculate profit
            $profit = $totalPrice - ($deductQuantity * $drug['cost_price']);
            $newQuantity = $drug['quantity'] - $deductQuantity;

            // Update drug quantity in the database
            $updateQuery = "UPDATE drugs SET quantity = :quantity WHERE id = :id";
            $updateStmt = $pdo->prepare($updateQuery);
            $updateStmt->execute(['quantity' => $newQuantity, 'id' => $drugId]);

            // Create a description that lists all the drugs bought from the cart
            $cartDrugs = array_map(function($item) { return $item['drugName'] . " (Qty: " . $item['quantity'] . ")"; }, $cartData['cart']); 
            $description = implode(", ", $cartDrugs);  // Join all drug names with their quantities

          // Modify the drug name if sale type is 'volume'
    $drugName = $item['drugName'];
    if ($saleType === 'volume') {
        $drugName .= " (Pack)";
    }
// Continue with the rest of the code without showing any failure message or skipping the transaction


            // Include customer in the sales and transactions
            $insertQuery = "INSERT INTO sales (drug_id, drug_name, quantity, total, username, receipt, payment_method1, payment_amount1, payment_method2, payment_amount2, profit, sale_date, sale_type, customer_id) 
            VALUES (:drug_id, :drug_name, :quantity, :total, :username, :receipt, :payment_method1, :payment_amount1, :payment_method2, :payment_amount2, :profit, NOW(), :sale_type, :customer_id)";
            $insertStmt = $pdo->prepare($insertQuery);
            $insertStmt->execute([
                ':drug_id' => $drugId,
                ':drug_name' =>$drugName,
                ':quantity' => $quantity,
                ':total' => $totalPrice,
                ':username' => $username,
                ':receipt' => $receipt,
                ':payment_method1' => $paymentMethod1,
                ':payment_amount1' => $totalPrice * $paymentAmount1PerSale,
                ':payment_method2' => $paymentMethod2,
                ':payment_amount2' => $totalPrice * $paymentAmount2PerSale,
                ':profit' => $profit,
                ':sale_type' => $saleType,
                ':customer_id' => $customer
            ]);

            // Store the last inserted ID
            $saleIds[] = $pdo->lastInsertId();
            $salesData[] = ['totalPrice' => $totalPrice, 'profit' => $profit];
            $activityDetails[] = "{$item['drugName']} (Qty: $quantity)";

            // Accumulate total amount and profit
            $totalAmount += $totalPrice;
            $totalProfit += $profit;
        }

        // Apply discount and update sales
        if ($totalAmount > 0 && $totalDiscount > 0) {
            foreach ($salesData as $index => $sale) {
                $discountForSale = ($sale['totalPrice'] / $totalAmount) * $totalDiscount;
                $adjustedTotal = $sale['totalPrice'] - $discountForSale;
                $adjustedProfit = $sale['profit'] - $discountForSale;

                $updateSalesQuery = "UPDATE sales 
                                      SET total = :adjustedTotal, profit = :adjustedProfit, discount = :discount 
                                      WHERE id = :saleId";
                $updateSalesStmt = $pdo->prepare($updateSalesQuery);
                $updateSalesStmt->execute([
                    'adjustedTotal' => $adjustedTotal,
                    'adjustedProfit' => $adjustedProfit,
                    'discount' => $discountForSale,
                    'saleId' => $saleIds[$index]
                ]);
            }
        }
// Log the action to drug history
$logQuery = "INSERT INTO drug_history (drug_id, action, quantity, details, user, action_date) 
             VALUES (:drug_id, :action, :quantity, :details, :user, NOW())";
$logStmt = $pdo->prepare($logQuery);
$logStmt->execute([
    ':drug_id' => $drugId,
    ':action' => 'Sold', // Specify the action performed
    ':quantity' => $deductQuantity, // Quantity deducted (volume or unit)
    ':details' => "Sold {$quantity} {$saleType} of {$drugName}. Remaining stock: {$newQuantity}.", // Action details
    ':user' => $username // Current user performing the action
]);
        // Insert into transactions table with customer information
        $insertTransactionQuery = "INSERT INTO transactions (activity_type, activity_details, activity_date, username, customer_id) 
        VALUES (:activity_type, :activity_details, NOW(), :username, :customer_id)";
        $insertTransactionStmt = $pdo->prepare($insertTransactionQuery);
        $insertTransactionStmt->execute([ 
            'activity_type' => 'Sell Drug',
            'activity_details' => implode(", ", $activityDetails),
            'username' => $username,
            'customer_id' => $customer
        ]);
 // Validate owing amount and owing type before inserting into owings table
 if (!empty($owingAmount) && !empty($owingType)) {

    if (!$customer) {
        echo json_encode(['success' => false, 'message' => 'Customer is required.']);
        exit;
    }

    // Query to fetch the customer's name and phone number from the customers table
    $customer_query = "SELECT full_name, phone_number FROM customers WHERE id = ?";
    $stmt = $pdo->prepare($customer_query);
    $stmt->execute([$customer]);
    $customerDetails = $stmt->fetch(PDO::FETCH_ASSOC);

    

    // Store customer details in variables
    $customer_name = $customerDetails['full_name'];  // Customer's name
    $phone_number = $customerDetails['phone_number'];  // Customer's phone number

    // Insert into the owings table if the owing amount and type are not empty
    $sql = "INSERT INTO owings (person_name, phone_number, amount, owing_type, description, created_by) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $customer_name,    // person_name (from customer details)
        $phone_number,     // phone_number (from customer details)
        $owingAmount,  // amount (from form input)
        $owingType, // owing_type (from form input)
        $description,      // description (list of drugs from the cart)
        $_SESSION['username']  // created_by (from session)
    ]);
}

        // Commit the transaction
        $pdo->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Sale completed successfully.',
            'receipt' => $receipt,
            'totalAmountAfterDiscount' => $totalAmount - $totalDiscount,
            'totalProfitAfterDiscount' => $totalProfit - $totalDiscount
        ]);
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>
