<?php
// Final version of the transfer handler - save as complete_transfer_handler.php in the same directory as productlist.php

// Set headers for JSON response
header('Content-Type: application/json');

// Disable error display but log errors
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

// Log function
function log_message($msg) {
    file_put_contents('transfer_final.log', date('[Y-m-d H:i:s] ') . $msg . "\n", FILE_APPEND);
}

log_message('Script started');

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$database = "ayula_store";

try {
    $conn = new mysqli($servername, $username, $password, $database);

    // Check connection
    if ($conn->connect_error) {
        log_message("Connection failed: " . $conn->connect_error);
        echo json_encode([
            'success' => false,
            'message' => 'Database connection failed: ' . $conn->connect_error
        ]);
        exit;
    }

    log_message("Connected to database successfully");
    log_message("POST data: " . json_encode($_POST));

    // Check if we have all required data
    if (!isset($_POST['action']) || $_POST['action'] != 'transfer_product' || 
        !isset($_POST['id_barang']) || !isset($_POST['quantity'])) {
        log_message("Missing required parameters");
        echo json_encode([
            'success' => false,
            'message' => 'Missing required parameters'
        ]);
        exit;
    }

    $id_barang = $_POST['id_barang'];
    $quantity = (int)$_POST['quantity'];

    log_message("Processing transfer for product ID: $id_barang, quantity: $quantity");

    // Validate inputs
    if (empty($id_barang) || $quantity <= 0) {
        log_message("Invalid input data");
        echo json_encode([
            'success' => false,
            'message' => 'ID barang atau jumlah tidak valid'
        ]);
        exit;
    }

    // Get product details with a simple query without JOIN to minimize errors
    $stmt = $conn->prepare("SELECT * FROM barang WHERE id_barang = ?");
    $stmt->bind_param("s", $id_barang);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 0) {
        log_message("Product not found");
        echo json_encode([
            'success' => false,
            'message' => 'Barang tidak ditemukan'
        ]);
        $stmt->close();
        exit;
    }

    $product = $result->fetch_assoc();
    log_message("Product found: " . json_encode($product));

    // Get the id_jenis directly from the database
    $jenis_stmt = $conn->prepare("SELECT id_jenis FROM jenis_barang WHERE id_jenis = ?");
    $jenis_stmt->bind_param("i", $product['id_jenis']);
    $jenis_stmt->execute();
    $jenis_result = $jenis_stmt->get_result();
    
    if ($jenis_result->num_rows == 0) {
        log_message("Product category not found");
        echo json_encode([
            'success' => false,
            'message' => 'Kategori barang tidak ditemukan'
        ]);
        $stmt->close();
        $jenis_stmt->close();
        exit;
    }
    
    $jenis_data = $jenis_result->fetch_assoc();
    $id_jenis = $jenis_data['id_jenis'];
    $jenis_stmt->close();

    // Check stock
    if ($quantity > $product['stok']) {
        log_message("Insufficient stock");
        echo json_encode([
            'success' => false,
            'message' => 'Stok tidak mencukupi'
        ]);
        $stmt->close();
        exit;
    }

    // Begin transaction
    $conn->begin_transaction();

    try {
        // 1. Update stock in barang table
        $new_stock = $product['stok'] - $quantity;
        $update_stmt = $conn->prepare("UPDATE barang SET stok = ? WHERE id_barang = ?");
        $update_stmt->bind_param("is", $new_stock, $id_barang);
        
        if (!$update_stmt->execute()) {
            throw new Exception("Failed to update product stock: " . $update_stmt->error);
        }
        
        log_message("Updated barang stock to: $new_stock");
        $update_stmt->close();

        // 2. Check if product exists in barang_kasir
        $check_stmt = $conn->prepare("SELECT * FROM barang_kasir WHERE kode_barang = ?");
        $check_stmt->bind_param("s", $product['kode_barang']);
        
        if (!$check_stmt->execute()) {
            throw new Exception("Failed to check if product exists in cashier: " . $check_stmt->error);
        }
        
        $check_result = $check_stmt->get_result();
        $timestamp = date('Y-m-d H:i:s');

        if ($check_result->num_rows > 0) {
            // 3a. Update existing product
            $kasir_product = $check_result->fetch_assoc();
            $new_kasir_stock = $kasir_product['stok'] + $quantity;
            
            log_message("Product exists in cashier, updating stock to: $new_kasir_stock");
            
            $kasir_update_stmt = $conn->prepare("UPDATE barang_kasir SET stok = ?, update_at = ? WHERE id_barangK = ?");
            $kasir_update_stmt->bind_param("isi", $new_kasir_stock, $timestamp, $kasir_product['id_barangK']);
            
            if (!$kasir_update_stmt->execute()) {
                throw new Exception("Failed to update cashier stock: " . $kasir_update_stmt->error);
            }
            
            $kasir_update_stmt->close();
        } else {
            // 3b. Insert new product
            log_message("Product does not exist in cashier, inserting new record");
            
            // Set default empty string for image
            $image = $product['image'] ?? '';
            
            $insert_stmt = $conn->prepare("INSERT INTO barang_kasir (kode_barang, nama_barang, id_jenis, harga, stok, gambar, created_at, update_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $insert_stmt->bind_param("ssisissss", 
                $product['kode_barang'],
                $product['nama_barang'],
                $id_jenis,
                $product['harga'],
                $quantity,
                $image,
                $timestamp,
                $timestamp
            );
            
            if (!$insert_stmt->execute()) {
                throw new Exception("Failed to insert product into cashier: " . $insert_stmt->error);
            }
            
            $insert_stmt->close();
        }
        
        $check_stmt->close();

        // Commit the transaction
        $conn->commit();
        
        log_message("Transfer completed successfully");
        
        echo json_encode([
            'success' => true,
            'message' => 'Berhasil memindahkan ' . $quantity . ' item ke kasir'
        ]);
        
    } catch (Exception $e) {
        // Rollback on error
        $conn->rollback();
        
        log_message("Error during transfer: " . $e->getMessage());
        
        echo json_encode([
            'success' => false,
            'message' => 'Terjadi kesalahan: ' . $e->getMessage()
        ]);
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    log_message("Unexpected error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Terjadi kesalahan tidak terduga: ' . $e->getMessage()
    ]);
}

// Close database connection
if (isset($conn)) {
    $conn->close();
}

log_message('Script completed');
?>