<?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 form data
        $color_id = intval($_POST['color_id']);
        $panel_type = $_POST['panel_type'];
        $master_color_id = intval($_POST['master_color_id']);
        
        // Validate color exists
        $validate_color_stmt = $conn->prepare("SELECT c.*, b.kode_buyer, b.nama_buyer, c.lemari, c.deskripsi 
                                               FROM master_color_panel c 
                                               JOIN buyers b ON c.buyer_id = b.id 
                                               WHERE c.id = ?");
        $validate_color_stmt->bind_param("i", $color_id);
        $validate_color_stmt->execute();
        $color_result = $validate_color_stmt->get_result();
        
        if ($color_result->num_rows == 0) {
            throw new Exception("Data warna tidak ditemukan");
        }
        
        $color_data = $color_result->fetch_assoc();
        $buyer_code = $color_data['kode_buyer'];
        $lemari = $color_data['lemari'];
        $deskripsi = $color_data['deskripsi'];
        
        // Get 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'] : [];
        
        // Validate that at least one component is provided
        if (empty($components) || count($components) == 0) {
            throw new Exception("Minimal harus ada satu komponen");
        }
        
        // Validate unique component selections
        $used_components = [];
        for ($i = 0; $i < count($components); $i++) {
            if ($components[$i] !== 'new' && in_array($components[$i], $used_components)) {
                throw new Exception("Komponen tidak boleh duplikat. Pilih komponen yang berbeda untuk setiap baris.");
            }
            if ($components[$i] !== 'new') {
                $used_components[] = $components[$i];
            }
        }
        
        // Function to get next sequential code
        function getNextSequentialCode($conn) {
            $codes = [];
            
            // From master_color
            $query1 = "SELECT code_color FROM master_color ORDER BY id DESC LIMIT 1";
            $result1 = $conn->query($query1);
            if ($result1->num_rows > 0) {
                $codes[] = intval($result1->fetch_assoc()['code_color']);
            }
            
            // From master_color_panel
            $query2 = "SELECT code_color FROM master_color_panel ORDER BY id DESC LIMIT 1";
            $result2 = $conn->query($query2);
            if ($result2->num_rows > 0) {
                $codes[] = intval($result2->fetch_assoc()['code_color']);
            }
            
            // From color_stock_items (now without CP. prefix, just numbers)
            $query3 = "SELECT kode_barang FROM color_stock_items ORDER BY id DESC LIMIT 1";
            $result3 = $conn->query($query3);
            if ($result3->num_rows > 0) {
                $last_code = $result3->fetch_assoc()['kode_barang'];
                $codes[] = intval($last_code); // Direct conversion since no prefix
            }
            
            // Get the maximum and add 1
            $next_number = empty($codes) ? 1 : max($codes) + 1;
            
            return $next_number;
        }
        
        $current_code = getNextSequentialCode($conn);
        
        // 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 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();
        $rack_data = $rack_result->fetch_assoc();
        $next_rack = $rack_data && $rack_data['max_rack'] ? $rack_data['max_rack'] + 1 : 1;
        
        // Get current date and expiry date
        $today = date('Y-m-d');
        $expiry_date = date('Y-m-d', strtotime('+6 months'));
        
        // Insert components and stock items
        for ($i = 0; $i < count($components); $i++) {
            $component_id = $components[$i];
            $quantity = intval($quantities[$i]);
            $available_quantity = intval($available_quantities[$i]);
            
            // Validate quantity values
            if ($quantity < 1) {
                throw new Exception("Jumlah komponen harus minimal 1");
            }
            
            if ($available_quantity < 0) {
                throw new Exception("Jumlah tersedia tidak boleh negatif");
            }
            
            // If "new" is selected, insert a new component
            if ($component_id === 'new') {
                $new_component_name = isset($new_components[$i]) ? trim($new_components[$i]) : '';
                $new_component_description = isset($new_component_descriptions[$i]) ? trim($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_component_stmt = $conn->prepare("SELECT id FROM color_components WHERE component_name = ?");
                $check_component_stmt->bind_param("s", $new_component_name);
                $check_component_stmt->execute();
                $check_component_result = $check_component_stmt->get_result();
                
                if ($check_component_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 (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;
            } else {
                // Validate existing component
                $validate_component_stmt = $conn->prepare("SELECT COUNT(*) as count FROM color_components WHERE id = ?");
                $validate_component_stmt->bind_param("i", $component_id);
                $validate_component_stmt->execute();
                $component_result = $validate_component_stmt->get_result();
                if ($component_result->fetch_assoc()['count'] == 0) {
                    throw new Exception("Komponen tidak valid");
                }
            }
            
            // Check if component already exists for this color
            $check_existing_stmt = $conn->prepare("SELECT COUNT(*) as count FROM color_panel_components WHERE color_id = ? AND component_id = ?");
            $check_existing_stmt->bind_param("ii", $color_id, $component_id);
            $check_existing_stmt->execute();
            $existing_result = $check_existing_stmt->get_result();
            if ($existing_result->fetch_assoc()['count'] > 0) {
                throw new Exception("Komponen ini sudah ada untuk warna ini");
            }
            
            // Get component name
            $component_query = "SELECT component_name FROM color_components 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();
            
            // Insert into color_panel_components
            $insert_panel_component_stmt = $conn->prepare("
                INSERT INTO color_panel_components (color_id, component_id, quantity, available_quantity)
                VALUES (?, ?, ?, ?)
            ");
            $insert_panel_component_stmt->bind_param("iiii", $color_id, $component_id, $quantity, $available_quantity);
            $insert_panel_component_stmt->execute();
            
            // Create stock items based on quantity and panel type
            // Stock items now use format 00003, 00004, etc (NO CP. PREFIX)
            if ($panel_type === 'copy_panel') {
                for ($j = 1; $j <= $quantity; $j++) {
                    $kode_barang = sprintf("%05d", $current_code++);
                    $rack_no = sprintf("%s.%03d", $lemari, $next_rack++);
                    
                    // Create keterangan
                    $keterangan = $buyer_code . ' ' . $deskripsi . ' ' . $component_data['component_name'];
                    if ($quantity > 1) {
                        $keterangan .= ' ' . $j;
                    }
                    
                    // Insert into color_stock_items
                    $insert_stock_stmt = $conn->prepare("
                        INSERT INTO color_stock_items (color_id, component_id, kode_barang, stock_number, status, lokasi, rack_no, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan, master_color_id, item_type)
                        VALUES (?, ?, ?, ?, 'Tersedia', 'Color Room', ?, ?, ?, ?, ?, 'copy_panel')
                    ");
                    $insert_stock_stmt->bind_param("iisissssi", $color_id, $component_id, $kode_barang, $j, $rack_no, $today, $expiry_date, $keterangan, $master_color_id);
                    $insert_stock_stmt->execute();
                }
            } else {
                // For master_color, create one item per component marked as master_color
                $kode_barang = sprintf("%05d", $current_code++);
                $rack_no = sprintf("%s.%03d", $lemari, $next_rack++);
                
                // Create keterangan
                $keterangan = $buyer_code . ' ' . $deskripsi . ' ' . $component_data['component_name'] . ' [MASTER]';
                
                // Insert into color_stock_items with item_type = 'master_color'
                $insert_stock_stmt = $conn->prepare("
                    INSERT INTO color_stock_items (color_id, component_id, kode_barang, stock_number, status, lokasi, rack_no, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan, master_color_id, item_type)
                    VALUES (?, ?, ?, 1, 'Tersedia', 'Color Room', ?, ?, ?, ?, ?, 'master_color')
                ");
                $insert_stock_stmt->bind_param("iissssssi", $color_id, $component_id, $kode_barang, $rack_no, $today, $expiry_date, $keterangan, $master_color_id);
                $insert_stock_stmt->execute();
            }
        }
        
        // Commit transaction
        $conn->commit();
        
        // Create log message
        $panel_type_text = $panel_type === 'master_color' ? 'Master Color' : 'Copy Panel';
        $log_message = "IT user added components to color panel (ID: $color_id, Type: $panel_type_text)";
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Add Component', $log_message);
        
        // Set success message
        $_SESSION['success_message'] = "Komponen berhasil ditambahkan ke panel warna!";
        
        // 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();
}
?>