<?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 panel data
        $buyer_id = $_POST['buyer_id'];
        $collection_surabaya_id = $_POST['collection_surabaya_id'];
        $code_color = trim($_POST['code_color']);
        $deskripsi = $_POST['deskripsi'];
        $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 that color code is not empty
        if (empty($code_color)) {
            throw new Exception("Kode warna tidak boleh kosong");
        }
        
        // Check if color code already exists
        $check_duplicate_stmt = $conn->prepare("SELECT COUNT(*) as count FROM master_color_panel_surabaya WHERE code_color = ?");
        $check_duplicate_stmt->bind_param("s", $code_color);
        $check_duplicate_stmt->execute();
        $duplicate_result = $check_duplicate_stmt->get_result();
        $duplicate_count = $duplicate_result->fetch_assoc()['count'];
        
        if ($duplicate_count > 0) {
            throw new Exception("Kode warna '$code_color' sudah ada di dalam database. Silakan gunakan kode warna yang berbeda.");
        }
        
        // 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_surabaya
        $validate_buyer_stmt = $conn->prepare("SELECT COUNT(*) as count FROM buyers_surabaya 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_surabaya_stmt = $conn->prepare("SELECT COUNT(*) as count FROM collection_surabayas WHERE id = ? AND buyer_id = ?");
        $validate_collection_surabaya_stmt->bind_param("ii", $collection_surabaya_id, $buyer_id);
        $validate_collection_surabaya_stmt->execute();
        $collection_surabaya_result = $validate_collection_surabaya_stmt->get_result();
        if ($collection_surabaya_result->fetch_assoc()['count'] == 0) {
            throw new Exception("Koleksi tidak valid untuk pembeli yang dipilih");
        }
        
        // Insert into master_color_panel_surabaya
        $insert_color_stmt = $conn->prepare("
            INSERT INTO master_color_panel_surabaya (code_color, deskripsi, buyer_id, collection_surabaya_id, lemari, status, kode_warna_hex, keterangan_warna)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $insert_color_stmt->bind_param("ssiissss", $code_color, $deskripsi, $buyer_id, $collection_surabaya_id, $lemari, $status, $kode_warna_hex, $keterangan_warna);
        $insert_color_stmt->execute();
        
        // Get the newly inserted color ID
        $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];
            }
        }
        
        // Get next available kode_barang number
        $next_code_query = "SELECT CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED) as num FROM color_stock_items_surabaya 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_surabaya 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 = 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_surabaya 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_surabaya (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_surabaya 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");
                }
            }
            
            // Insert into color_panel_components_surabaya
            $insert_panel_component_stmt = $conn->prepare("
                INSERT INTO color_panel_components_surabaya (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();
            
            // 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++);
                
                // Get buyer and component info for keterangan
                $buyer_query = "SELECT nama_buyer, kode_buyer FROM buyers_surabaya 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();
                
                $component_query = "SELECT component_name FROM color_components_surabaya 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();
                
                // Create keterangan
                $keterangan = $buyer_data['kode_buyer'] . ' ' . $code_color . ' ' . $component_data['component_name'];
                if ($quantity > 1) {
                    $keterangan .= ' ' . $j;
                }
                
                // Insert into color_stock_items_surabaya
                $insert_stock_stmt = $conn->prepare("
                    INSERT INTO color_stock_items_surabaya (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 Color Data', "IT user added new color data: $code_color");
        
        // Set success message
        $_SESSION['success_message'] = "Data warna '$code_color' berhasil ditambahkan";
        
        // 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();
}
?>