<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Process the form data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Start transaction
        $conn->begin_transaction();
        
        // Get color ID
        $color_id = $_POST['color_id'];
        
        // Get color info
        $color_query = "SELECT c.*, b.kode_buyer, b.nama_buyer 
                      FROM master_color_panel_semarang c 
                      JOIN buyers_semarang b ON c.buyer_id = b.id 
                      WHERE c.id = ?";
        $color_stmt = $conn->prepare($color_query);
        $color_stmt->bind_param("i", $color_id);
        $color_stmt->execute();
        $color_result = $color_stmt->get_result();
        
        if ($color_result->num_rows === 0) {
            throw new Exception("Data warna tidak ditemukan");
        }
        
        $color_data = $color_result->fetch_assoc();
        $code_color = $color_data['code_color'];
        $lemari = $color_data['lemari'];
        $buyer_code = $color_data['kode_buyer'];
        
        // Process component data
        $components = $_POST['components'];
        $quantities = $_POST['quantities'];
        $available_quantities = $_POST['available_quantities'];
        $new_components = isset($_POST['new_components']) ? $_POST['new_components'] : [];
        $new_component_descriptions = isset($_POST['new_component_descriptions']) ? $_POST['new_component_descriptions'] : [];
        
        // Get next available kode_barang number
        $next_code_query = "SELECT CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED) as num FROM color_stock_items_semarang ORDER BY num DESC LIMIT 1";
        $next_code_result = $conn->query($next_code_query);
        $next_code = $next_code_result->num_rows > 0 ? $next_code_result->fetch_assoc()['num'] + 1 : 1;
        
        // Prepare to track rack numbers by lemari
        $rack_query = "SELECT MAX(CAST(SUBSTRING(rack_no, 3) AS UNSIGNED)) as max_rack 
                      FROM color_stock_items_semarang WHERE rack_no LIKE ?";
        $rack_stmt = $conn->prepare($rack_query);
        $rack_prefix = $lemari . '.%';
        $rack_stmt->bind_param("s", $rack_prefix);
        $rack_stmt->execute();
        $rack_result = $rack_stmt->get_result();
        $next_rack = $rack_result->num_rows > 0 ? $rack_result->fetch_assoc()['max_rack'] + 1 : 1;
        
        // Insert components and stock items
        for ($i = 0; $i < count($components); $i++) {
            $component_id = $components[$i];
            $quantity = $quantities[$i];
            $available_quantity = $available_quantities[$i];
            
            // If "new" is selected, insert a new component
            if ($component_id === 'new') {
                $new_component_name = $new_components[$i] ?? '';
                $new_component_description = $new_component_descriptions[$i] ?? '';
                
                if (empty($new_component_name)) {
                    throw new Exception("Nama komponen baru tidak boleh kosong");
                }
                
                // Check if component name already exists
                $check_stmt = $conn->prepare("SELECT id FROM color_components_semarang WHERE component_name = ?");
                $check_stmt->bind_param("s", $new_component_name);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    throw new Exception("Komponen dengan nama '$new_component_name' sudah ada");
                }
                
                // Insert new component
                $insert_component_stmt = $conn->prepare("
                    INSERT INTO color_components_semarang (component_name, description)
                    VALUES (?, ?)
                ");
                $insert_component_stmt->bind_param("ss", $new_component_name, $new_component_description);
                $insert_component_stmt->execute();
                
                // Get the newly inserted component ID
                $component_id = $conn->insert_id;
            }
            
            // Check if the component already exists for this color
            $check_component_stmt = $conn->prepare("
                SELECT id, quantity, available_quantity FROM color_panel_components_semarang 
                WHERE color_id = ? AND component_id = ?
            ");
            $check_component_stmt->bind_param("ii", $color_id, $component_id);
            $check_component_stmt->execute();
            $check_component_result = $check_component_stmt->get_result();
            
            if ($check_component_result->num_rows > 0) {
                // Component exists, update quantity
                $component_data = $check_component_result->fetch_assoc();
                $new_quantity = $component_data['quantity'] + $quantity;
                $new_available_quantity = $component_data['available_quantity'] + $available_quantity;
                
                $update_component_stmt = $conn->prepare("
                    UPDATE color_panel_components_semarang 
                    SET quantity = ?, available_quantity = ? 
                    WHERE color_id = ? AND component_id = ?
                ");
                $update_component_stmt->bind_param("ddii", $new_quantity, $new_available_quantity, $color_id, $component_id);
                $update_component_stmt->execute();
            } else {
                // Component doesn't exist, insert new
                $insert_panel_component_stmt = $conn->prepare("
                    INSERT INTO color_panel_components_semarang (color_id, component_id, quantity, available_quantity)
                    VALUES (?, ?, ?, ?)
                ");
                $insert_panel_component_stmt->bind_param("iidd", $color_id, $component_id, $quantity, $available_quantity);
                $insert_panel_component_stmt->execute();
            }
            
            // Get component name for keterangan
            $component_query = "SELECT component_name FROM color_components_semarang WHERE id = ?";
            $component_stmt = $conn->prepare($component_query);
            $component_stmt->bind_param("i", $component_id);
            $component_stmt->execute();
            $component_result = $component_stmt->get_result();
            $component_data = $component_result->fetch_assoc();
            
            // Get the current date and add 6 months for expiration date
            $today = date('Y-m-d');
            $expiry_date = date('Y-m-d', strtotime('+6 months'));
            
            // Create stock items based on quantity
            for ($j = 1; $j <= $quantity; $j++) {
                $kode_barang = sprintf("CP.%04d", $next_code++);
                $rack_no = sprintf("%s.%03d", $lemari, $next_rack++);
                
                // Create keterangan
                $keterangan = $buyer_code . ' ' . $code_color . ' ' . $component_data['component_name'];
                if ($quantity > 1) {
                    $keterangan .= ' ' . $j;
                }
                
                // Insert into color_stock_items_semarang
                $insert_stock_stmt = $conn->prepare("
                    INSERT INTO color_stock_items_semarang (color_id, component_id, kode_barang, stock_number, status, lokasi, rack_no, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan)
                    VALUES (?, ?, ?, ?, 'Tersedia', 'Color Room', ?, ?, ?, ?)
                ");
                $insert_stock_stmt->bind_param("iisissss", $color_id, $component_id, $kode_barang, $j, $rack_no, $today, $expiry_date, $keterangan);
                $insert_stock_stmt->execute();
            }
        }
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Add Component', "IT user added components to color: $code_color (ID: $color_id)");
        
        // Set success message
        $_SESSION['success_message'] = "Komponen berhasil ditambahkan ke warna $code_color";
        
        // Redirect back to the form
        header("Location: add_component_it.php");
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        
        // Set error message
        $_SESSION['error_message'] = "Gagal menambahkan komponen: " . $e->getMessage();
        
        // Redirect back to the form
        header("Location: add_component_it.php");
        exit();
    }
} else {
    // Redirect if not POST request
    header("Location: add_component_it.php");
    exit();
}
?>