<?php
// File: /artist/paintings_handler.php
session_start();
include '../db.php'; 

ini_set('display_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    die("Access Denied. Please login.");
}

$artist_id = $_SESSION['user_id'];

// --- 1. SMART WATERMARK FUNCTION (Transparent Logo OR Text) ---
function applyWatermark($sourceFile, $targetFile, $watermarkText) {
    // 1. Load Main Image
    $info = getimagesize($sourceFile);
    $mime = $info['mime'];
    
    switch ($mime) {
        case 'image/jpeg': $image = imagecreatefromjpeg($sourceFile); break;
        case 'image/png':  $image = imagecreatefrompng($sourceFile); break;
        case 'image/webp': $image = imagecreatefromwebp($sourceFile); break;
        default: return false; 
    }

    $mainW = imagesx($image);
    $mainH = imagesy($image);

    // --- OPTION A: LOGO WATERMARK (Priority) ---
    // Make sure your logo at '../images/ucf_logo.png' is a transparent PNG.
    $logoPath = '../images/ucf_logo.png'; 

    if (file_exists($logoPath)) {
        $logo = imagecreatefrompng($logoPath);
        
        // Get Logo Dimensions
        $logoW = imagesx($logo);
        $logoH = imagesy($logo);

        // Calculate New Size (e.g., 25% of the main image width)
        $newLogoW = $mainW * 0.25; 
        $ratio = $logoH / $logoW;
        $newLogoH = $newLogoW * $ratio;

        // Create Canvas for Resized Logo
        $resizedLogo = imagecreatetruecolor($newLogoW, $newLogoH);
        
        // Important: Maintain transparency channel during resize
        imagealphablending($resizedLogo, false);
        imagesavealpha($resizedLogo, true);
        // Fill with transparent background before resizing onto it
        $transparent = imagecolorallocatealpha($resizedLogo, 255, 255, 255, 127);
        imagefilledrectangle($resizedLogo, 0, 0, $newLogoW, $newLogoH, $transparent);
        
        // Resize
        imagecopyresampled($resizedLogo, $logo, 0, 0, 0, 0, $newLogoW, $newLogoH, $logoW, $logoH);

        // Calculate Center Position
        $x = ($mainW / 2) - ($newLogoW / 2);
        $y = ($mainH / 2) - ($newLogoH / 2);

        // --- APPLY TRANSPARENCY MERGE ---
        // The last number (30) is opacity from 0 (invisible) to 100 (solid).
        // 30 makes it 70% transparent, which is good for watermarks.
        imagecopymerge($image, $resizedLogo, $x, $y, 0, 0, $newLogoW, $newLogoH, 30);
        
        imagedestroy($logo);
        imagedestroy($resizedLogo);

    } else {
        // --- OPTION B: TEXT FALLBACK (If no logo found) ---
        $fontPath = '../admin/font.ttf'; 
        
        if (file_exists($fontPath)) {
            // Big Text Setup
            $fontSize = $mainW * 0.10; // 10% size
            $angle = 45;
            
            // Text Box
            $bbox = imagettfbbox($fontSize, $angle, $fontPath, $watermarkText);
            $textW = $bbox[2] - $bbox[0];
            $textH = $bbox[1] - $bbox[7];
            
            $x = ($mainW / 2) - ($textW / 2);
            $y = ($mainH / 2) + ($textH / 2);

            // Colors (Alpha 60 = semi-transparent)
            $white = imagecolorallocatealpha($image, 255, 255, 255, 60); 
            $black = imagecolorallocatealpha($image, 0, 0, 0, 60);       

            // Draw Shadow & Text
            imagettftext($image, $fontSize, $angle, $x+5, $y+5, $black, $fontPath, $watermarkText);
            imagettftext($image, $fontSize, $angle, $x, $y, $white, $fontPath, $watermarkText);
        } else {
            // System Font Fallback
            $font = 5;
            $white = imagecolorallocate($image, 255, 255, 255);
            $x = ($mainW / 2) - (imagefontwidth($font) * strlen($watermarkText) / 2);
            $y = ($mainH / 2);
            imagestring($image, $font, $x, $y, $watermarkText, $white);
        }
    }

    // Save Final Image
    if ($mime == 'image/jpeg') imagejpeg($image, $targetFile, 90);
    elseif ($mime == 'image/png') imagepng($image, $targetFile, 9);
    elseif ($mime == 'image/webp') imagewebp($image, $targetFile, 90);

    imagedestroy($image);
    return true;
}

// --- 2. UPLOAD HANDLER ---
function handleImageUpload($file, $watermark_text = "UCF") {
    $target_dir = "../uploads/paintings/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
    
    if ($file['error'] !== UPLOAD_ERR_OK) return false;

    $ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
    $allowed_types = ['jpg', 'jpeg', 'png', 'webp'];
    if (!in_array($ext, $allowed_types)) die("Error: File type not allowed.");

    $new_name = uniqid('art_') . "." . $ext;
    $target_file = $target_dir . $new_name;
    
    // Apply Watermark
    if (applyWatermark($file["tmp_name"], $target_file, $watermark_text)) {
        return "uploads/paintings/" . $new_name; 
    }
    
    // Fallback
    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        return "uploads/paintings/" . $new_name; 
    }
    return false;
}

// ========================================================
// 1. ADD PAINTING
// ========================================================
if (isset($_POST['add_painting'])) {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $price = floatval($_POST['price']);
    $sale_price = !empty($_POST['sale_price']) ? floatval($_POST['sale_price']) : NULL;
    $size = trim($_POST['size_dimensions']);
    $medium = trim($_POST['medium']);
    $category = trim($_POST['subject_category']);
    $tags = trim($_POST['tags']);
    $copyright = isset($_POST['copyright']) ? 1 : 0;

    $wm_text = "UCF"; // Only used if Logo is missing

    if (!empty($_FILES['painting_image']['name'])) {
        $image_path = handleImageUpload($_FILES['painting_image'], $wm_text);
        if (!$image_path) die("Error: Failed to upload image.");
    } else {
        die("Error: Image is required.");
    }

    $sql = "INSERT INTO paintings (artist_id, title, description, price, sale_price, image_path, size_dimensions, medium, subject_category, tags, copyright_confirmed, uploaded_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("issdssssssi", $artist_id, $title, $description, $price, $sale_price, $image_path, $size, $medium, $category, $tags, $copyright);
    
    if ($stmt->execute()) {
        header("Location: paintings.php?status=success");
        exit();
    } else {
        die("Database Error: " . $stmt->error);
    }
}

// ========================================================
// 2. EDIT PAINTING
// ========================================================
if (isset($_POST['edit_painting'])) {
    $p_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $price = floatval($_POST['price']);
    $sale_price = !empty($_POST['sale_price']) ? floatval($_POST['sale_price']) : NULL;
    $size = trim($_POST['size_dimensions']);
    $medium = trim($_POST['medium']);
    $category = trim($_POST['subject_category']);
    $tags = trim($_POST['tags']);
    $copyright = isset($_POST['copyright']) ? 1 : 0;

    $image_path = $_POST['existing_image_path'];
    $wm_text = "UCF";

    if (!empty($_FILES['painting_image']['name'])) {
        $uploaded_path = handleImageUpload($_FILES['painting_image'], $wm_text);
        if ($uploaded_path) $image_path = $uploaded_path; 
    }

    $sql = "UPDATE paintings SET title=?, description=?, price=?, sale_price=?, image_path=?, size_dimensions=?, medium=?, subject_category=?, tags=?, copyright_confirmed=? WHERE id=? AND artist_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssdssssssiii", $title, $description, $price, $sale_price, $image_path, $size, $medium, $category, $tags, $copyright, $p_id, $artist_id);
    
    if ($stmt->execute()) {
        header("Location: paintings.php?status=updated");
        exit();
    } else {
        die("Database Error: " . $stmt->error);
    }
}

// ========================================================
// 3. DELETE PAINTING
// ========================================================
if (isset($_POST['delete_painting'])) {
    $p_id = filter_var($_POST['painting_id'], FILTER_SANITIZE_NUMBER_INT);
    $stmt = $conn->prepare("DELETE FROM paintings WHERE id=? AND artist_id=?");
    $stmt->bind_param("ii", $p_id, $artist_id);
    if ($stmt->execute()) {
        header("Location: paintings.php?status=deleted");
        exit();
    }
}
?>