<?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 = 'master_color'; // Always master_color now
        $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_number = $_POST['lemari_number'];
        $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 name_color is not empty
        if (empty($name_color)) {
            throw new Exception("Nama warna tidak boleh kosong");
        }
        
        // Validate lemari_number
        if (!in_array($lemari_number, ['1', '2'])) {
            throw new Exception("Lemari harus berupa angka 1 atau 2");
        }
        
        // Validate lemari (should be a single letter A-Z)
        if (!preg_match('/^[A-Z]$/', $lemari)) {
            throw new Exception("Huruf 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");
        }
        
        // Check if the lemari location is already occupied
        $location_check_stmt = $conn->prepare("
            SELECT COUNT(*) as count 
            FROM master_color 
            WHERE lemari_number = ? AND lemari = ?
        ");
        $location_check_stmt->bind_param("ss", $lemari_number, $lemari);
        $location_check_stmt->execute();
        $location_result = $location_check_stmt->get_result();
        $location_data = $location_result->fetch_assoc();
        
        if ($location_data['count'] > 0) {
            throw new Exception("Lokasi Lemari {$lemari_number} - Posisi {$lemari} sudah terisi. Silakan pilih posisi lain.");
        }
        
        // Generate codes sequentially
        $current_code = $next_code_number;
        
        // 1. Insert into master_color
        $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, lemari_number, status, kode_warna_hex, keterangan_warna)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $insert_master_color_stmt->bind_param("ssiisssss", $master_color_code, $name_color, $buyer_id, $collection_id, $lemari, $lemari_number, $status, $kode_warna_hex, $keterangan_warna);
        $insert_master_color_stmt->execute();
        $master_color_id = $conn->insert_id;
        
        // 2. Insert into master_color_panel
        $panel_code = sprintf("%05d", $current_code++);
        $insert_panel_stmt = $conn->prepare("
            INSERT INTO master_color_panel (code_color, deskripsi, buyer_id, collection_id, lemari, lemari_number, status, kode_warna_hex, keterangan_warna, master_color_id, panel_type)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $insert_panel_stmt->bind_param("ssiisssssis", $panel_code, $name_color, $buyer_id, $collection_id, $lemari, $lemari_number, $status, $kode_warna_hex, $keterangan_warna, $master_color_id, $panel_type);
        $insert_panel_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        $log_message = "IT user added new Master Color: Master Color Code: $master_color_code, Panel Code: $panel_code ($name_color) - Lemari $lemari_number-$lemari";
        log_activity($conn, $it_id, 'it', 'Add Master Color Data', $log_message);
        
        $_SESSION['success_message'] = "Master Color berhasil ditambahkan! Master Color: $master_color_code, Panel: $panel_code ($name_color) - Lemari $lemari_number-$lemari";
        
        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();
}
?>