<?php
// delete_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'];

// Get color ID from query string
$color_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($color_id <= 0) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid color ID']);
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get color details before deletion
    $color_query = "SELECT c.code_color, c.deskripsi, c.master_color_id, mc.code_color as master_code
                   FROM master_color_panel c
                   LEFT JOIN master_color mc ON c.master_color_id = mc.id
                   WHERE c.id = ?";
    $color_stmt = $conn->prepare($color_query);
    $color_stmt->bind_param("i", $color_id);
    $color_stmt->execute();
    $color_result = $color_stmt->get_result();
    
    if ($color_result->num_rows == 0) {
        throw new Exception("Data warna tidak ditemukan");
    }
    
    $color_data = $color_result->fetch_assoc();
    $code_color = $color_data['code_color'];
    $deskripsi = $color_data['deskripsi'];
    $master_color_id = $color_data['master_color_id'];
    $master_code = $color_data['master_code'];
    
    // Check if any items are borrowed
    $check_borrowed_stmt = $conn->prepare("
        SELECT COUNT(*) as count 
        FROM color_stock_items 
        WHERE color_id = ? AND status = 'Dipinjam'
    ");
    $check_borrowed_stmt->bind_param("i", $color_id);
    $check_borrowed_stmt->execute();
    $borrowed_result = $check_borrowed_stmt->get_result();
    $borrowed_count = $borrowed_result->fetch_assoc()['count'];
    
    if ($borrowed_count > 0) {
        throw new Exception("Tidak dapat menghapus data warna karena masih ada item yang sedang dipinjam");
    }
    
    // Delete in correct order to respect foreign key constraints
    
    // 1. Delete from transaction_items (if any references exist)
    $delete_transaction_items_stmt = $conn->prepare("
        DELETE FROM transaction_items 
        WHERE stock_item_id IN (SELECT id FROM color_stock_items WHERE color_id = ?)
    ");
    $delete_transaction_items_stmt->bind_param("i", $color_id);
    $delete_transaction_items_stmt->execute();
    
    // 2. Delete from approval_history
    $delete_approval_history_stmt = $conn->prepare("
        DELETE FROM approval_history 
        WHERE color_approval_id IN (SELECT id FROM color_approvals WHERE color_id = ?)
    ");
    $delete_approval_history_stmt->bind_param("i", $color_id);
    $delete_approval_history_stmt->execute();
    
    // 3. Delete from color_approvals
    $delete_approvals_stmt = $conn->prepare("DELETE FROM color_approvals WHERE color_id = ?");
    $delete_approvals_stmt->bind_param("i", $color_id);
    $delete_approvals_stmt->execute();
    
    // 4. Delete from color_stock_items
    $delete_stock_stmt = $conn->prepare("DELETE FROM color_stock_items WHERE color_id = ?");
    $delete_stock_stmt->bind_param("i", $color_id);
    $delete_stock_stmt->execute();
    
    // 5. Delete from color_panel_components
    $delete_components_stmt = $conn->prepare("DELETE FROM color_panel_components WHERE color_id = ?");
    $delete_components_stmt->bind_param("i", $color_id);
    $delete_components_stmt->execute();
    
    // 6. Delete from master_color_panel
    $delete_panel_stmt = $conn->prepare("DELETE FROM master_color_panel WHERE id = ?");
    $delete_panel_stmt->bind_param("i", $color_id);
    $delete_panel_stmt->execute();
    
    // 7. Delete from master_color if exists and no other panels reference it
    if ($master_color_id) {
        // Check if other panels still reference this master_color
        $check_refs_stmt = $conn->prepare("SELECT COUNT(*) as count FROM master_color_panel WHERE master_color_id = ?");
        $check_refs_stmt->bind_param("i", $master_color_id);
        $check_refs_stmt->execute();
        $refs_result = $check_refs_stmt->get_result();
        $refs_count = $refs_result->fetch_assoc()['count'];
        
        // If no other panels reference it, delete the master_color
        if ($refs_count == 0) {
            $delete_master_stmt = $conn->prepare("DELETE FROM master_color WHERE id = ?");
            $delete_master_stmt->bind_param("i", $master_color_id);
            $delete_master_stmt->execute();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Log activity
    $log_message = "IT user deleted color data (Panel: $code_color, Master: " . ($master_code ?? 'N/A') . "): $deskripsi";
    log_activity($conn, $it_id, 'it', 'Delete Color Data', $log_message);
    
    // Return success response
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => "Data warna '$code_color' ($deskripsi) berhasil dihapus beserta semua data terkait"
    ]);
    
} catch (Exception $e) {
    // Rollback transaction
    $conn->rollback();
    
    // Return error response
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>