<?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
        $panel_type = $_POST['panel_type']; // 'master_color' or 'copy_panel'
        $next_code_number = intval($_POST['next_code_number']);
        $buyer_id = $_POST['buyer_id'];
        $collection_id = $_POST['collection_id'];
        $name_color = trim($_POST['name_color']);
        $lemari = strtoupper($_POST['lemari']);
        $status = $_POST['status'];
        $kode_warna_hex = $_POST['kode_warna_hex'] ? $_POST['kode_warna_hex'] : null;
        $keterangan_warna = $_POST['keterangan_warna'] ? $_POST['keterangan_warna'] : null;
        
        // Validate panel type
        if (!in_array($panel_type, ['master_color', 'copy_panel'])) {
            throw new Exception("Tipe panel tidak valid");
        }
        
        // Validate that name_color is not empty
        if (empty($name_color)) {
            throw new Exception("Nama warna tidak boleh kosong");
        }
        
        // Validate lemari (should be a single letter A-Z)
        if (!preg_match('/^[A-Z]$/', $lemari)) {
            throw new Exception("Lemari harus berupa 1 huruf abjad (A-Z)");
        }
        
        // Validate hex code if provided
        if ($kode_warna_hex && !preg_match('/^[0-9A-Fa-f]{6}$/', $kode_warna_hex)) {
            throw new Exception("Kode warna hex harus berupa 6 karakter hexadecimal");
        }
        
        // Validate buyer and collection
        $validate_buyer_stmt = $conn->prepare("SELECT COUNT(*) as count FROM buyers WHERE id = ?");
        $validate_buyer_stmt->bind_param("i", $buyer_id);
        $validate_buyer_stmt->execute();
        $buyer_result = $validate_buyer_stmt->get_result();
        if ($buyer_result->fetch_assoc()['count'] == 0) {
            throw new Exception("Pembeli tidak valid");
        }
        
        $validate_collection_stmt = $conn->prepare("SELECT COUNT(*) as count FROM collections WHERE id = ? AND buyer_id = ?");
        $validate_collection_stmt->bind_param("ii", $collection_id, $buyer_id);
        $validate_collection_stmt->execute();
        $collection_result = $validate_collection_stmt->get_result();
        if ($collection_result->fetch_assoc()['count'] == 0) {
            throw new Exception("Koleksi tidak valid untuk pembeli yang dipilih");
        }
        
        // Generate codes sequentially (ALL WITHOUT PREFIX)
        $current_code = $next_code_number;
        
        // 1. Insert into master_color (code: 00001)
        $master_color_code = sprintf("%05d", $current_code++);
        $insert_master_color_stmt = $conn->prepare("
            INSERT INTO master_color (code_color, name_color, buyer_id, collection_id, lemari, status, kode_warna_hex, keterangan_warna)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $insert_master_color_stmt->bind_param("ssiissss", $master_color_code, $name_color, $buyer_id, $collection_id, $lemari, $status, $kode_warna_hex, $keterangan_warna);
        $insert_master_color_stmt->execute();
        $master_color_id = $conn->insert_id;
        
        // 2. Insert into master_color_panel (code: 00002)
        $panel_code = sprintf("%05d", $current_code++);
        $insert_panel_stmt = $conn->prepare("
            INSERT INTO master_color_panel (code_color, deskripsi, buyer_id, collection_id, lemari, status, kode_warna_hex, keterangan_warna, master_color_id, panel_type)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $insert_panel_stmt->bind_param("ssiissssis", $panel_code, $name_color, $buyer_id, $collection_id, $lemari, $status, $kode_warna_hex, $keterangan_warna, $master_color_id, $panel_type);
        $insert_panel_stmt->execute();
        $color_id = $conn->insert_id;
        
        // 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'] : [];
        
        // 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];
            }
        }
        
        // 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'));
        
        // Get buyer info for keterangan
        $buyer_query = "SELECT nama_buyer, kode_buyer FROM buyers WHERE id = ?";
        $buyer_stmt = $conn->prepare($buyer_query);
        $buyer_stmt->bind_param("i", $buyer_id);
        $buyer_stmt->execute();
        $buyer_result = $buyer_stmt->get_result();
        $buyer_data = $buyer_result->fetch_assoc();
        
        // 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");
                }
            }
            
            // 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
            // 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_data['kode_buyer'] . ' ' . $name_color . ' ' . $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_data['kode_buyer'] . ' ' . $name_color . ' ' . $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 new color data ($panel_type_text): Master Color Code: $master_color_code, Panel Code: $panel_code ($name_color)";
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Add Color Data', $log_message);
        
        // Set success message
        $_SESSION['success_message'] = "Data warna berhasil ditambahkan! Master Color: $master_color_code, Panel: $panel_code ($name_color) - Tipe: $panel_type_text";
        
        // Redirect back to the form
        header("Location: new_data_it.php");
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        
        // Set error message
        $_SESSION['error_message'] = "Gagal menambahkan data warna: " . $e->getMessage();
        
        // Redirect back to the form
        header("Location: new_data_it.php");
        exit();
    }
} else {
    // Redirect if not POST request
    header("Location: new_data_it.php");
    exit();
}
?>