<?php
session_start();
require_once "../config/connection.php";

// Check if user is logged in as IT
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

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

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

try {
    $color_id = intval($_POST['color_id']);
    $component_id = intval($_POST['component_id']);
    $quantity = intval($_POST['quantity']);
    $tanggal_pembuatan = $_POST['tanggal_pembuatan'];
    $tanggal_kedaluwarsa = $_POST['tanggal_kedaluwarsa'];
    $keterangan = trim($_POST['keterangan']);
    
    // Validate input
    if ($color_id <= 0 || $component_id <= 0 || $quantity <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid input data']);
        exit();
    }
    
    if (empty($tanggal_pembuatan) || empty($tanggal_kedaluwarsa)) {
        echo json_encode(['success' => false, 'message' => 'Tanggal pembuatan dan kedaluwarsa harus diisi']);
        exit();
    }
    
    // Validate dates
    if (strtotime($tanggal_kedaluwarsa) <= strtotime($tanggal_pembuatan)) {
        echo json_encode(['success' => false, 'message' => 'Tanggal kedaluwarsa harus setelah tanggal pembuatan']);
        exit();
    }
    
    // Get color and component info
    $info_query = "
        SELECT 
            mcp.code_color,
            cc.component_name
        FROM master_color_panel mcp, color_components cc
        WHERE mcp.id = ? AND cc.id = ?
    ";
    $info_stmt = $conn->prepare($info_query);
    $info_stmt->bind_param('ii', $color_id, $component_id);
    $info_stmt->execute();
    $info_result = $info_stmt->get_result();
    
    if ($info_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Color panel atau component tidak ditemukan']);
        exit();
    }
    
    $info_data = $info_result->fetch_assoc();
    
    // Check if component exists in color panel
    $panel_comp_check = $conn->prepare("SELECT id FROM color_panel_components WHERE color_id = ? AND component_id = ?");
    $panel_comp_check->bind_param('ii', $color_id, $component_id);
    $panel_comp_check->execute();
    $panel_comp_result = $panel_comp_check->get_result();
    
    if ($panel_comp_result->num_rows == 0) {
        echo json_encode(['success' => false, 'message' => 'Component tidak terdaftar untuk color panel ini']);
        exit();
    }
    
    // Get the next stock number for this color and component
    $next_stock_query = "
        SELECT COALESCE(MAX(stock_number), 0) + 1 as next_stock_number
        FROM color_stock_items 
        WHERE color_id = ? AND component_id = ?
    ";
    $next_stock_stmt = $conn->prepare($next_stock_query);
    $next_stock_stmt->bind_param('ii', $color_id, $component_id);
    $next_stock_stmt->execute();
    $next_stock_result = $next_stock_stmt->get_result();
    $next_stock_data = $next_stock_result->fetch_assoc();
    
    $success_count = 0;
    $failed_items = [];
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        for ($i = 0; $i < $quantity; $i++) {
            $current_stock_number = $next_stock_data['next_stock_number'] + $i;
            
            // Generate unique kode_barang
            $kode_barang = 'CP.' . str_pad((getNextKodeBarangNumber($conn)), 4, '0', STR_PAD_LEFT);
            
            // Generate QR code (simplified base64 image)
            $qr_code = generateSimpleQRCode($kode_barang);
            
            // Generate rack number based on color lemari
            $rack_query = "SELECT lemari FROM master_color_panel WHERE id = ?";
            $rack_stmt = $conn->prepare($rack_query);
            $rack_stmt->bind_param('i', $color_id);
            $rack_stmt->execute();
            $rack_result = $rack_stmt->get_result();
            $rack_data = $rack_result->fetch_assoc();
            
            $rack_no = $rack_data['lemari'] . '.' . str_pad($current_stock_number, 3, '0', STR_PAD_LEFT);
            
            // Insert stock item
            $insert_query = "
                INSERT INTO color_stock_items 
                (color_id, component_id, kode_barang, stock_number, status, lokasi, rack_no, qr_code, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan)
                VALUES (?, ?, ?, ?, 'Tersedia', 'Color Room', ?, ?, ?, ?, ?)
            ";
            
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bind_param('iisisssss', 
                $color_id, 
                $component_id, 
                $kode_barang, 
                $current_stock_number, 
                $rack_no, 
                $qr_code,
                $tanggal_pembuatan, 
                $tanggal_kedaluwarsa, 
                $keterangan
            );
            
            if ($insert_stmt->execute()) {
                $success_count++;
            } else {
                $failed_items[] = "Stock #" . $current_stock_number . ": " . $conn->error;
            }
        }
        
        // Update available quantity in color_panel_components
        if ($success_count > 0) {
            $update_query = "
                UPDATE color_panel_components 
                SET available_quantity = available_quantity + ? 
                WHERE color_id = ? AND component_id = ?
            ";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bind_param('iii', $success_count, $color_id, $component_id);
            $update_stmt->execute();
        }
        
        $conn->commit();
        
        // Log the activity
        $it_id = $_SESSION['user_id'];
        $details = "Added {$success_count} stock items for component '{$info_data['component_name']}' in color '{$info_data['code_color']}'";
        create_audit_log($conn, 'Add Stock Items', $it_id, 'it', $details);
        
        $message = "Berhasil menambahkan {$success_count} stock item";
        if (!empty($failed_items)) {
            $message .= ". Gagal: " . implode(', ', $failed_items);
        }
        
        echo json_encode([
            'success' => true,
            'message' => $message,
            'added_count' => $success_count
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

// Helper function to get next kode barang number
function getNextKodeBarangNumber($conn) {
    $query = "SELECT COALESCE(MAX(CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED)), 0) + 1 as next_number FROM color_stock_items WHERE kode_barang LIKE 'CP.%'";
    $result = $conn->query($query);
    $row = $result->fetch_assoc();
    return $row['next_number'];
}

// Helper function to generate simple QR code (placeholder)
function generateSimpleQRCode($text) {
    // This is a simplified QR code generator
    // In production, you might want to use a proper QR code library
    $data = base64_encode($text);
    return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6AQMAAACyIsh+AAAABlBMVEX///8AAABVwtN+AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAA/ElEQVRoge3YQQ6EIAwF0CZzgDkSV+dIHsBEobRQZpAU3bj4Xeggb9XUFocIgXhdfA+JWH7tpA92gDUg9wR2vXQbAH5QEhwN5cwD3Aa5UjeA56AuAe6CVqoUONXdBoAXtJGkjfRyZgHMgInP+DGAD+RS5XzHBLho08VSAC9I98ALbakM+v4A4AC5VMubT5xl0td/I4A18DON1NtGAOABvDB73AgIYB20KMdMaald0QJ4QDsmkZZvbgmjAyfAHLSjuw4nHklh+GcRwBQc9cNcR9JfIwVYAWQTDPAEkAynHFQDwA9KbuXUKRP+opECTEAdSebDsitaAB9AIF4VJ5sFuEwcnCI6AAAAAElFTkSuQmCC";
}
?>