<?php
// File: /artist/index.php

// --- STEP 1: FORCE ERROR DISPLAY ---
// This is a temporary measure to make hidden errors visible.
ini_set('display_errors', 1);
error_reporting(E_ALL);

include 'header.php'; // This starts the session and includes db.php

// --- DYNAMIC DATA FETCHING ---
// Security checks are handled in header.php

// Check if the database connection object exists from the included header
if (!isset($conn) || $conn->connect_error) {
    die("<div class='p-8 text-red-600 bg-red-100'>Database connection failed. Please contact support.</div>");
}

$artist_id = $_SESSION['user_id'];

// 1. Fetch Artist's First Name
$artistFirstName = "Artist"; // Default value
$stmt_name = $conn->prepare("SELECT first_name FROM artist_profiles WHERE user_id = ?");
if ($stmt_name === false) { die("SQL Prepare Error (artist_name): " . htmlspecialchars($conn->error)); }

$stmt_name->bind_param("i", $artist_id);
if ($stmt_name->execute()) {
    $result_name = $stmt_name->get_result();
    if ($row_name = $result_name->fetch_assoc()) {
        $artistFirstName = !empty($row_name['first_name']) ? $row_name['first_name'] : "Artist";
    }
} else {
    die("SQL Execute Error (artist_name): " . htmlspecialchars($stmt_name->error));
}
$stmt_name->close();

// 2. Fetch Total Paintings
$totalPaintings = 0;
$stmt_paintings = $conn->prepare("SELECT COUNT(id) as painting_count FROM paintings WHERE artist_id = ?");
if ($stmt_paintings === false) { die("SQL Prepare Error (paintings_count): " . htmlspecialchars($conn->error)); }

$stmt_paintings->bind_param("i", $artist_id);
if ($stmt_paintings->execute()) {
    $result_paintings = $stmt_paintings->get_result();
    if ($row_paintings = $result_paintings->fetch_assoc()) {
        $totalPaintings = $row_paintings['painting_count'];
    }
} else {
     die("SQL Execute Error (paintings_count): " . htmlspecialchars($stmt_paintings->error));
}
$stmt_paintings->close();

// 3. Fetch Total Sales
$totalSales = 0;
$stmt_sales = $conn->prepare("
    SELECT SUM(oi.price_at_purchase) as total_revenue
    FROM order_items oi
    JOIN paintings p ON oi.painting_id = p.id
    JOIN orders o ON oi.order_id = o.id
    WHERE p.artist_id = ? AND o.payment_status = 'completed'
");
if ($stmt_sales === false) { die("SQL Prepare Error (total_sales): " . htmlspecialchars($conn->error)); }

$stmt_sales->bind_param("i", $artist_id);
if ($stmt_sales->execute()) {
    $result_sales = $stmt_sales->get_result();
    if ($row_sales = $result_sales->fetch_assoc()) {
        $totalSales = $row_sales['total_revenue'] ?? 0;
    }
} else {
    die("SQL Execute Error (total_sales): " . htmlspecialchars($stmt_sales->error));
}
$stmt_sales->close();


// 4. Calculate Profile Completion
$profileCompletion = 0;
$stmt_profile = $conn->prepare("SELECT first_name, last_name, phone, address, profile_image_path, bank_name, bank_account_iban FROM artist_profiles WHERE user_id = ?");
if ($stmt_profile === false) { die("SQL Prepare Error (profile_completion): " . htmlspecialchars($conn->error)); }

$stmt_profile->bind_param("i", $artist_id);
if ($stmt_profile->execute()) {
    $result_profile = $stmt_profile->get_result();
    if ($profile_data = $result_profile->fetch_assoc()) {
        $total_fields = 7;
        $filled_fields = 0;
        if (!empty($profile_data['first_name'])) $filled_fields++;
        if (!empty($profile_data['last_name'])) $filled_fields++;
        if (!empty($profile_data['phone'])) $filled_fields++;
        if (!empty($profile_data['address'])) $filled_fields++;
        if (isset($profile_data['profile_image_path']) && $profile_data['profile_image_path'] !== 'default_avatar.png') $filled_fields++;
        if (!empty($profile_data['bank_name'])) $filled_fields++;
        if (!empty($profile_data['bank_account_iban'])) $filled_fields++;
        
        if ($total_fields > 0) {
            $profileCompletion = round(($filled_fields / $total_fields) * 100);
        }
    }
} else {
    die("SQL Execute Error (profile_completion): " . htmlspecialchars($stmt_profile->error));
}
$stmt_profile->close();


// 5. Fetch Subscription Expiry Date
$subscriptionExpires = "N/A";
$stmt_sub = $conn->prepare("SELECT end_date FROM artist_subscriptions WHERE user_id = ? ORDER BY end_date DESC LIMIT 1");
if ($stmt_sub === false) { die("SQL Prepare Error (subscription): " . htmlspecialchars($conn->error)); }

$stmt_sub->bind_param("i", $artist_id);
if ($stmt_sub->execute()) {
    $result_sub = $stmt_sub->get_result();
    if ($row_sub = $result_sub->fetch_assoc()) {
        $subscriptionExpires = date("M d, Y", strtotime($row_sub['end_date']));
    }
} else {
    die("SQL Execute Error (subscription): " . htmlspecialchars($stmt_sub->error));
}
$stmt_sub->close();

?>

<!-- Main Content (HTML remains the same) -->
<div class="p-6 md:p-8 bg-gray-50 min-h-screen">
    <!-- 1. Welcome Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-ucf-charcoal">Dashboard</h1>
        <p class="text-lg text-gray-600">Welcome back, <?php echo htmlspecialchars($artistFirstName); ?>!</p>
    </div>

    <!-- 2. Colorful Stats Cards Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">

        <!-- Total Paintings Card -->
        <div class="relative p-6 rounded-lg shadow-lg text-white bg-gradient-to-br from-ucf-green to-teal-600 overflow-hidden">
            <i class="fas fa-palette absolute -right-4 -bottom-4 text-white opacity-20 text-8xl"></i>
            <p class="text-sm font-medium uppercase tracking-wider">Total Paintings</p>
            <p class="text-4xl font-bold mt-2"><?php echo $totalPaintings; ?></p>
        </div>

        <!-- Total Sales Card -->
        <div class="relative p-6 rounded-lg shadow-lg text-white bg-gradient-to-br from-blue-500 to-indigo-600 overflow-hidden">
             <i class="fas fa-dollar-sign absolute -right-4 -bottom-4 text-white opacity-20 text-8xl"></i>
            <p class="text-sm font-medium uppercase tracking-wider">Total Sales</p>
            <p class="text-4xl font-bold mt-2">₹<?php echo number_format($totalSales); ?></p>
        </div>

        <!-- Profile Completion Card -->
        <div class="p-6 rounded-lg shadow-lg bg-white">
            <p class="text-sm font-medium text-gray-500 uppercase">Profile Completion</p>
            <div class="flex items-center justify-between mt-2">
                <p class="text-4xl font-bold text-ucf-charcoal"><?php echo $profileCompletion; ?>%</p>
                <div class="w-16 h-16 bg-yellow-100 flex items-center justify-center rounded-full">
                    <i class="fas fa-user-check text-yellow-500 text-3xl"></i>
                </div>
            </div>
            <!-- Progress Bar -->
            <div class="w-full bg-gray-200 rounded-full h-2.5 mt-4">
                <div class="bg-yellow-500 h-2.5 rounded-full" style="width: <?php echo $profileCompletion; ?>%"></div>
            </div>
        </div>
        
        <!-- Subscription Card -->
        <div class="relative p-6 rounded-lg shadow-lg text-white bg-gradient-to-br from-ucf-charcoal to-gray-800 overflow-hidden">
             <i class="fas fa-calendar-alt absolute -right-4 -bottom-4 text-white opacity-20 text-8xl"></i>
            <p class="text-sm font-medium uppercase tracking-wider">Subscription</p>
            <p class="text-xl font-bold mt-2">Expires:</p>
            <p class="text-2xl font-semibold"><?php echo $subscriptionExpires; ?></p>
        </div>

    </div> <!-- / End Stats Grid -->

    <!-- 3. Combined Actions & Activity Section -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Quick Actions -->
        <div class="lg:col-span-1 bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-2xl font-bold text-ucf-charcoal mb-4">Quick Actions</h2>
            <div class="flex flex-col space-y-3">
                <a href="paintings.php?action=add" class="bg-ucf-green text-white font-bold py-3 px-4 rounded-lg hover:bg-ucf-green-dark transition-all duration-300 transform hover:scale-105 flex items-center justify-center">
                    <i class="fas fa-plus-circle mr-2"></i> Add New Painting
                </a>
                <a href="profile.php" class="bg-ucf-charcoal text-white font-bold py-3 px-4 rounded-lg hover:bg-gray-700 transition-all duration-300 transform hover:scale-105 flex items-center justify-center">
                    <i class="fas fa-edit mr-2"></i> Edit My Profile
                </a>
                <a href="orders.php" class="bg-gray-200 text-ucf-charcoal font-bold py-3 px-4 rounded-lg hover:bg-gray-300 transition-all duration-300 transform hover:scale-105 flex items-center justify-center">
                    <i class="fas fa-receipt mr-2"></i> View My Sales
                </a>
            </div>
        </div>

        <!-- Recent Activity Feed (Currently Static) -->
        <div class="lg:col-span-2 bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-2xl font-bold text-ucf-charcoal mb-4">Recent Activity</h2>
            <ul class="divide-y divide-gray-200">
                <!-- Activity Item 1 -->
                <li class="py-4 flex items-center">
                    <div class="bg-green-100 h-10 w-10 flex items-center justify-center rounded-full mr-4">
                        <i class="fas fa-receipt text-green-600"></i>
                    </div>
                    <p class="text-gray-700 flex-grow">New Sale: "Sunset Over the Lake" was sold for ₹2,500.</p>
                    <span class="ml-4 text-sm text-gray-500 whitespace-nowrap">2 hours ago</span>
                </li>
                <!-- Activity Item 2 -->
                <li class="py-4 flex items-center">
                    <div class="bg-blue-100 h-10 w-10 flex items-center justify-center rounded-full mr-4">
                        <i class="fas fa-palette text-blue-600"></i>
                    </div>
                    <p class="text-gray-700 flex-grow">You uploaded a new painting: "City at Night".</p>
                    <span class="ml-4 text-sm text-gray-500 whitespace-nowrap">1 day ago</span>
                </li>
                 <!-- Activity Item 3 -->
                <li class="py-4 flex items-center">
                    <div class="bg-yellow-100 h-10 w-10 flex items-center justify-center rounded-full mr-4">
                        <i class="fas fa-star text-yellow-600"></i>
                    </div>
                    <p class="text-gray-700 flex-grow">Your painting "Mountain Majesty" received a new favorite.</p>
                    <span class="ml-4 text-sm text-gray-500 whitespace-nowrap">3 days ago</span>
                </li>
            </ul>
        </div>
    </div>

</div>

<?php include 'footer.php'; ?>

