<?php
// init.php ko shaamil karein
require_once 'init.php';

// Suraksha jaanch
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: dashboard.php");
    exit();
}
$employee_id = (int)$_GET['id'];

// --- DATA FETCHING ---
// 1. Karmachari ki poori jaankari
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $employee_id);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();
if (!$employee) {
    header("Location: employees.php");
    exit();
}
$stmt->close();

// 2. Karmachari ke sabhi roles
$roles_stmt = $conn->prepare("SELECT r.name FROM roles r JOIN user_roles ur ON r.id = ur.role_id WHERE ur.user_id = ?");
$roles_stmt->bind_param("i", $employee_id);
$roles_stmt->execute();
$roles_result = $roles_stmt->get_result();
$employee_roles = [];
while ($row = $roles_result->fetch_assoc()) { $employee_roles[] = $row['name']; }
$roles_stmt->close();
$employee['role_display'] = implode(', ', $employee_roles);
$is_smm_profile = in_array('SMM', $employee_roles);

// --- DASHBOARD CARDS DATA ---
// **YAHAN MUKHYA BADLAV KIYA GAYA HAI**
if ($is_smm_profile) {
    // SMM ke liye: Kul bache hue checklist tasks
    $remaining_tasks_stmt = $conn->prepare("SELECT COUNT(id) as total FROM tasks WHERE assigned_user_id = ? AND is_checklist_task = TRUE AND status NOT IN ('Completed', 'Skipped')");
} else {
    // Baaki sabhi users ke liye: Kul bache hue non-checklist tasks
    $remaining_tasks_stmt = $conn->prepare("SELECT COUNT(id) as total FROM tasks WHERE assigned_user_id = ? AND is_checklist_task = FALSE AND status NOT IN ('Completed', 'Skipped')");
}

// Kul bache hue tasks
$remaining_tasks_stmt->bind_param("i", $employee_id);
$remaining_tasks_stmt->execute();
$total_remaining_tasks = $remaining_tasks_stmt->get_result()->fetch_assoc()['total'];
$remaining_tasks_stmt->close();


// 2. Overall Career Rating (Sahi Formula ke saath)
$career_rating = 0;
// Career mein kul assigned tasks
$total_assigned_stmt = $conn->prepare("SELECT COUNT(id) as total FROM tasks WHERE assigned_user_id = ?");
$total_assigned_stmt->bind_param("i", $employee_id);
$total_assigned_stmt->execute();
$total_career_assigned = $total_assigned_stmt->get_result()->fetch_assoc()['total'];
$total_assigned_stmt->close();

// Career mein kul completed tasks
$total_completed_stmt = $conn->prepare("SELECT COUNT(id) as total FROM tasks WHERE assigned_user_id = ? AND status = 'Completed'");
$total_completed_stmt->bind_param("i", $employee_id);
$total_completed_stmt->execute();
$total_career_completed = $total_completed_stmt->get_result()->fetch_assoc()['total'];
$total_completed_stmt->close();

if ($total_career_assigned > 0) {
    $career_rating = min(5, ($total_career_completed / $total_career_assigned) * 5);
}


// --- MONTHLY REPORTING DATA ---
$selected_month = $_GET['month'] ?? date('Y-m');
$start_of_selected_month = $selected_month . '-01';
$end_of_selected_month = date('Y-m-t', strtotime($start_of_selected_month));

$sql = "SELECT 
            COUNT(id) as total_completed,
            SUM(rejection_count > 0) as total_rejections
        FROM tasks
        WHERE assigned_user_id = ? AND status = 'Completed' AND completed_at BETWEEN ? AND ?";
$stmt = $conn->prepare($sql);
$start_datetime = $start_of_selected_month . ' 00:00:00';
$end_datetime = $end_of_selected_month . ' 23:59:59';
$stmt->bind_param("iss", $employee_id, $start_datetime, $end_datetime);
$stmt->execute();
$monthly_report_result = $stmt->get_result();
$monthly_report = $monthly_report_result->fetch_assoc();
$stmt->close();

$assigned_sql = "SELECT COUNT(id) as total_assigned FROM tasks WHERE assigned_user_id = ? AND assigned_date BETWEEN ? AND ?";
$stmt_assigned = $conn->prepare($assigned_sql);
$stmt_assigned->bind_param("iss", $employee_id, $start_of_selected_month, $end_of_selected_month);
$stmt_assigned->execute();
$monthly_report['total_assigned'] = $stmt_assigned->get_result()->fetch_assoc()['total_assigned'];
$stmt_assigned->close();

$conn->close();

require_once 'header.php';
?>

<title>Employee Profile - <?php echo htmlspecialchars($employee['name']); ?></title>

<div class="flex-1" x-data="{ isProfileModalOpen: false }">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">Employee Profile</h2>
    </header>

<main class="p-6 md:p-10">
    <div class="bg-white p-6 rounded-lg shadow-lg mb-8">
        <div class="flex flex-col md:flex-row justify-between items-start">
            <div>
                <h2 class="text-3xl font-bold text-gray-900"><?php echo htmlspecialchars($employee['name']); ?></h2>
                <p class="text-lg text-gray-600"><?php echo htmlspecialchars($employee['role_display']); ?></p>
                <button @click="isProfileModalOpen = true" class="mt-2 text-sm text-blue-600 hover:underline">View Full Profile Details</button>
            </div>
             <?php if (userHasRole(['Admin', 'Manager'])): ?>
                <a href="edit-employee.php?id=<?php echo $employee_id; ?>" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg shadow-sm mt-4 md:mt-0">Edit Profile</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-red-100 p-3 rounded-full"><svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg></div>
            <div>
                <p class="text-sm font-medium text-gray-500">Total Active Tasks</p>
                <p class="text-2xl font-bold text-gray-800"><?php echo $total_remaining_tasks; ?> Tasks</p>
                <p class="text-xs text-gray-400 mt-1">Daily Target: <?php echo htmlspecialchars($employee['daily_target']); ?></p>
            </div>
        </div>
        
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-yellow-100 p-3 rounded-full"><svg class="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.539 1.118l-3.975-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.196-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118L2.05 10.1c-.783-.57-.38-1.81.588-1.81h4.914a1 1 0 00.95-.69L9.53 2.927z"/></svg></div>
            <div><p class="text-sm font-medium text-gray-500">Career Rating</p><p class="text-2xl font-bold text-gray-800"><?php echo round($career_rating, 2); ?> / 5</p></div>
        </div>
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-purple-100 p-3 rounded-full"><svg class="h-6 w-6 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg></div>
            <div><p class="text-sm font-medium text-gray-500">Production (This Month)</p><p class="text-2xl font-bold text-gray-800"><?php echo ($monthly_report['total_assigned'] ?? 0) > 0 ? round(($monthly_report['total_completed'] / $monthly_report['total_assigned']) * 100, 1) : 0; ?>%</p></div>
        </div>
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-teal-100 p-3 rounded-full"><svg class="h-6 w-6 text-teal-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg></div>
            <div><p class="text-sm font-medium text-gray-500">Quality (This Month)</p><p class="text-2xl font-bold text-gray-800"><?php echo ($monthly_report['total_completed'] ?? 0) > 0 ? round((($monthly_report['total_completed'] - $monthly_report['total_rejections']) / $monthly_report['total_completed']) * 100, 1) : 100; ?>%</p></div>
        </div>
    </div>

    <div class="bg-white p-6 rounded-lg shadow-lg">
        <div class="flex flex-col md:flex-row justify-between items-center mb-4 gap-4">
            <h3 class="text-xl font-bold">Monthly Performance Summary</h3>
            <form method="GET" action="employee-profile.php">
                <input type="hidden" name="id" value="<?php echo $employee_id; ?>">
                <input type="month" name="month" value="<?php echo htmlspecialchars($selected_month); ?>" class="border-gray-300 rounded-md shadow-sm" onchange="this.form.submit()">
            </form>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr><th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Month</th><th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Completed Tasks</th><th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Production</th><th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Quality</th><th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rating</th></tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($monthly_report) || $monthly_report['total_completed'] == 0): ?>
                        <tr><td colspan="5" class="px-6 py-4 text-center text-gray-500">No completed tasks found for this month.</td></tr>
                    <?php else: 
                        $production = ($monthly_report['total_assigned'] > 0) ? round(($monthly_report['total_completed'] / $monthly_report['total_assigned']) * 100, 1) . '%' : 'N/A';
                        $quality = ($monthly_report['total_completed'] > 0) ? round((($monthly_report['total_completed'] - $monthly_report['total_rejections']) / $monthly_report['total_completed']) * 100, 1) . '%' : '100%';
                        $working_days = date('t', strtotime($selected_month));
                        $monthly_target = $employee['daily_target'] * $working_days;
                        $rating = ($monthly_target > 0) ? min(5, round(($monthly_report['total_completed'] / $monthly_target) * 5, 2)) : 0;
                    ?>
                        <tr>
                            <td class="px-6 py-4 font-semibold"><?php echo date("F Y", strtotime($selected_month)); ?></td>
                            <td class="px-6 py-4"><?php echo $monthly_report['total_completed']; ?></td>
                            <td class="px-6 py-4"><?php echo $production; ?></td>
                            <td class="px-6 py-4"><?php echo $quality; ?></td>
                            <td class="px-6 py-4 font-bold"><?php echo $rating; ?> / 5</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div x-show="isProfileModalOpen" x-transition ... class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" @keydown.escape.window="isProfileModalOpen = false">
    <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-2xl" @click.away="isProfileModalOpen = false">
        <div class="flex justify-between items-center border-b pb-3 mb-6"><h3 class="text-2xl font-semibold">Full Profile Details</h3><button @click="isProfileModalOpen = false" class="text-gray-500 hover:text-gray-800">&times;</button></div>
        <dl class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
            <div class="border-b py-2"><dt class="font-semibold text-gray-600">Full Name</dt><dd class="text-gray-800"><?php echo htmlspecialchars($employee['name']); ?></dd></div>
            <div class="border-b py-2"><dt class="font-semibold text-gray-600">Father's Name</dt><dd class="text-gray-800"><?php echo htmlspecialchars($employee['father_name'] ?? 'N/A'); ?></dd></div>
            <div class="border-b py-2"><dt class="font-semibold text-gray-600">Login Email</dt><dd class="text-gray-800"><?php echo htmlspecialchars($employee['email']); ?></dd></div>
            <div class="border-b py-2"><dt class="font-semibold text-gray-600">Joining Date</dt><dd class="text-gray-800"><?php echo date("d M, Y", strtotime($employee['joining_date'])); ?></dd></div>
            <div class="border-b py-2"><dt class="font-semibold text-gray-600">Contact Number</dt><dd class="text-gray-800"><?php echo htmlspecialchars($employee['contact_no'] ?? 'N/A'); ?></dd></div>
            <div class="border-b py-2"><dt class="font-semibold text-gray-600">Emergency Number</dt><dd class="text-gray-800"><?php echo htmlspecialchars($employee['emergency_number'] ?? 'N/A'); ?></dd></div>
            <div class="md:col-span-2 border-b py-2"><dt class="font-semibold text-gray-600">Address</dt><dd class="text-gray-800 whitespace-pre-wrap"><?php echo htmlspecialchars($employee['address'] ?? 'N/A'); ?></dd></div>
        </dl>
        <div class="flex justify-end mt-8"><button type="button" @click="isProfileModalOpen = false" class="px-6 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">Close</button></div>
    </div>
</div>

</div> 
<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>