<?php
session_start();
require_once '../../assets/db_connect.php';

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

if (!isset($_SESSION['user']['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

try {
    $pdo->beginTransaction();
    
    // Get form data
    $product_id = $_POST['product_id'] ?? 0;
    $supplier_id = $_POST['supplier_id'] ?? 0;
    $invoice_no = $_POST['invoice_no'] ?? '';
    $purchase_date = $_POST['purchase_date'] ?? date('Y-m-d');
    $batch_no = $_POST['batch_no'] ?? '';
    $qty = $_POST['qty'] ?? 0;
    $cost_price = $_POST['cost_price'] ?? 0;
    $sell_price = $_POST['sell_price'] ?? 0;
    $expiry_date = $_POST['expiry_date'] ?? null;
    $shop_id = $_POST['shop_id'] ?? $_SESSION['user']['shop_id'];
    $created_by = $_POST['created_by'] ?? $_SESSION['user']['id'];
    
    // Validate
    if (empty($invoice_no) || $qty <= 0 || $cost_price <= 0) {
        throw new Exception('Please fill all required fields');
    }
    
    // Create purchase record
    $purchase_sql = "INSERT INTO purchases (supplier_id, invoice_no, purchase_date, created_by, shop_id) 
                     VALUES (?, ?, ?, ?, ?)";
    $purchase_stmt = $pdo->prepare($purchase_sql);
    $purchase_stmt->execute([$supplier_id, $invoice_no, $purchase_date, $created_by, $shop_id]);
    $purchase_id = $pdo->lastInsertId();
    
    // Create batch record
    $batch_sql = "INSERT INTO product_batches (product_id, batch_no, cost_price, sell_price, 
                  expiry_date, supplier_id, created_by, shop_id) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $batch_stmt = $pdo->prepare($batch_sql);
    $batch_stmt->execute([$product_id, $batch_no, $cost_price, $sell_price, 
                         $expiry_date, $supplier_id, $created_by, $shop_id]);
    $batch_id = $pdo->lastInsertId();
    
    // Create purchase line
    $line_sql = "INSERT INTO purchase_lines (purchase_id, batch_id, qty, cost_price) 
                 VALUES (?, ?, ?, ?)";
    $line_stmt = $pdo->prepare($line_sql);
    $line_stmt->execute([$purchase_id, $batch_id, $qty, $cost_price]);
    
    // Create inventory movement
    $movement_sql = "INSERT INTO inventory_movements (product_id, batch_id, change_qty, 
                     movement_type, reference_id, created_by, shop_id) 
                     VALUES (?, ?, ?, 'PURCHASE', ?, ?, ?)";
    $movement_stmt = $pdo->prepare($movement_sql);
    $movement_stmt->execute([$product_id, $batch_id, $qty, $purchase_id, $created_by, $shop_id]);
    
    // Update purchase total
    $total = $qty * $cost_price;
    $update_sql = "UPDATE purchases SET total = ? WHERE id = ?";
    $update_stmt = $pdo->prepare($update_sql);
    $update_stmt->execute([$total, $purchase_id]);
    
    $pdo->commit();
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Purchase saved successfully!',
        'purchase_id' => $purchase_id,
        'total' => $total
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>