<?php
// Start session
session_start();

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

// Set content type to JSON
header('Content-Type: application/json');

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode(['success' => false, 'message' => 'Akses tidak diizinkan']);
    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']);
        $code_color = trim($_POST['code_color']);
        $deskripsi = trim($_POST['deskripsi']);
        $lemari = strtoupper(trim($_POST['lemari']));
        $status = $_POST['status'];
        $kode_warna_hex = !empty($_POST['kode_warna_hex']) ? trim($_POST['kode_warna_hex']) : null;
        $keterangan_warna = !empty($_POST['keterangan_warna']) ? trim($_POST['keterangan_warna']) : null;
        
        // Validate that color code is not empty
        if (empty($code_color)) {
            throw new Exception("Kode warna tidak boleh kosong");
        }
        
        // Validate color_id
        if ($color_id <= 0) {
            throw new Exception("ID warna tidak valid");
        }
        
        // Check if color exists
        $check_color_stmt = $conn->prepare("SELECT code_color FROM master_color_panel WHERE id = ?");
        $check_color_stmt->bind_param("i", $color_id);
        $check_color_stmt->execute();
        $check_color_result = $check_color_stmt->get_result();
        
        if ($check_color_result->num_rows == 0) {
            throw new Exception("Data warna tidak ditemukan");
        }
        
        $original_color = $check_color_result->fetch_assoc();
        
        // Check if color code already exists (excluding current color)
        $check_duplicate_stmt = $conn->prepare("SELECT COUNT(*) as count FROM master_color_panel WHERE code_color = ? AND id != ?");
        $check_duplicate_stmt->bind_param("si", $code_color, $color_id);
        $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");
        }
        
        // Update master_color_panel
        $update_color_stmt = $conn->prepare("
            UPDATE master_color_panel 
            SET code_color = ?, deskripsi = ?, lemari = ?, status = ?, kode_warna_hex = ?, keterangan_warna = ?
            WHERE id = ?
        ");
        $update_color_stmt->bind_param("ssssssi", $code_color, $deskripsi, $lemari, $status, $kode_warna_hex, $keterangan_warna, $color_id);
        $update_color_stmt->execute();
        
        // If color code changed, update keterangan in stock items
        if ($original_color['code_color'] !== $code_color) {
            // Get buyer info for updating keterangan
            $buyer_query = "SELECT b.kode_buyer 
                           FROM buyers b 
                           JOIN master_color_panel c ON b.id = c.buyer_id 
                           WHERE c.id = ?";
            $buyer_stmt = $conn->prepare($buyer_query);
            $buyer_stmt->bind_param("i", $color_id);
            $buyer_stmt->execute();
            $buyer_result = $buyer_stmt->get_result();
            $buyer_data = $buyer_result->fetch_assoc();
            
            // Update keterangan in stock items
            $update_stock_stmt = $conn->prepare("
                UPDATE color_stock_items csi
                JOIN color_components cc ON csi.component_id = cc.id
                SET csi.keterangan = CONCAT(?, ' ', ?, ' ', cc.component_name, 
                    CASE 
                        WHEN csi.stock_number > 1 THEN CONCAT(' ', csi.stock_number)
                        ELSE ''
                    END)
                WHERE csi.color_id = ?
            ");
            $update_stock_stmt->bind_param("ssi", $buyer_data['kode_buyer'], $code_color, $color_id);
            $update_stock_stmt->execute();
        }
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Update Color Data', "IT user updated color data: $code_color (ID: $color_id)");
        
        echo json_encode([
            'success' => true, 
            'message' => "Data warna '$code_color' berhasil diperbarui"
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        
        echo json_encode([
            'success' => false, 
            'message' => $e->getMessage()
        ]);
    }
} else {
    echo json_encode([
        'success' => false, 
        'message' => 'Method tidak diizinkan'
    ]);
}
?>