<?php
// update_color_data.php
session_start();
require_once "../config/connection.php";

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    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']);
        $deskripsi = trim($_POST['deskripsi']);
        $lemari = strtoupper($_POST['lemari']);
        $status = $_POST['status'];
        $kode_warna_hex = !empty($_POST['kode_warna_hex']) ? $_POST['kode_warna_hex'] : null;
        $keterangan_warna = !empty($_POST['keterangan_warna']) ? $_POST['keterangan_warna'] : null;
        
        // Validate color exists
        $validate_stmt = $conn->prepare("SELECT code_color, master_color_id FROM master_color_panel WHERE id = ?");
        $validate_stmt->bind_param("i", $color_id);
        $validate_stmt->execute();
        $validate_result = $validate_stmt->get_result();
        
        if ($validate_result->num_rows == 0) {
            throw new Exception("Data warna tidak ditemukan");
        }
        
        $color_data = $validate_result->fetch_assoc();
        $master_color_id = $color_data['master_color_id'];
        
        // Validate deskripsi is not empty
        if (empty($deskripsi)) {
            throw new Exception("Deskripsi 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");
        }
        
        // Update master_color_panel
        $update_panel_stmt = $conn->prepare("
            UPDATE master_color_panel 
            SET deskripsi = ?, lemari = ?, status = ?, kode_warna_hex = ?, keterangan_warna = ?
            WHERE id = ?
        ");
        $update_panel_stmt->bind_param("sssssi", $deskripsi, $lemari, $status, $kode_warna_hex, $keterangan_warna, $color_id);
        $update_panel_stmt->execute();
        
        // Update master_color if exists
        if ($master_color_id) {
            $update_master_stmt = $conn->prepare("
                UPDATE master_color 
                SET name_color = ?, lemari = ?, status = ?, kode_warna_hex = ?, keterangan_warna = ?
                WHERE id = ?
            ");
            $update_master_stmt->bind_param("sssssi", $deskripsi, $lemari, $status, $kode_warna_hex, $keterangan_warna, $master_color_id);
            $update_master_stmt->execute();
        }
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Update Color Data', "IT user updated color data (ID: $color_id): $deskripsi");
        
        // Return success response
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'message' => 'Data warna berhasil diupdate'
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        
        // Return error response
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
} else {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
}
?>