<?php
session_start();
include 'db.php';

// Redirect if not logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: auth.php");
    exit;
}

$id = $_SESSION['user_id'];
$msg = "";

/* Fetch user details */
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$user = $stmt->fetch();

/* Fetch user's orders */
$orderStmt = $pdo->prepare("
    SELECT id, total_amount, payment_status, awb_number, created_at 
    FROM orders 
    WHERE user_id = ? 
    ORDER BY id DESC
");
$orderStmt->execute([$id]);
$orders = $orderStmt->fetchAll(PDO::FETCH_ASSOC);

/* Update profile */
if (isset($_POST['update'])) {
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone']);

    if (!empty($_POST['password'])) {
        $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $update = $pdo->prepare("UPDATE users SET name=?, phone=?, password=? WHERE id=?");
        $update->execute([$name, $phone, $pass, $id]);
    } else {
        $update = $pdo->prepare("UPDATE users SET name=?, phone=? WHERE id=?");
        $update->execute([$name, $phone, $id]);
    }

    // Refresh user details
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
    $stmt->execute([$id]);
    $user = $stmt->fetch();

    $msg = "Profile updated successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile – Varahi Foods</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-gray-100 font-[Poppins]">

<?php include "header.php"; ?>

<div class="min-h-[80vh] px-4 py-10 max-w-3xl mx-auto">

    <!-- PROFILE SECTION -->
    <div class="bg-white rounded-xl shadow-lg p-7 mb-10 relative">

        <h2 class="text-2xl font-bold text-blue-900 mb-4">My Profile</h2>

        <!-- Edit Button -->
        <button onclick="toggleEdit()" 
                class="absolute top-7 right-7 text-blue-900 hover:text-blue-700 text-xl">
            ✏️
        </button>

        <?php if ($msg): ?>
            <p class="text-green-600 mb-3"><?= $msg ?></p>
        <?php endif; ?>

        <!-- VIEW MODE -->
        <div id="viewMode">
            <p class="mb-2"><strong>Name:</strong> <?= htmlspecialchars($user['name']) ?></p>
            <p class="mb-2"><strong>Phone:</strong> <?= htmlspecialchars($user['phone']) ?></p>
            <p class="mb-2"><strong>Email:</strong> <?= htmlspecialchars($user['email']) ?></p>
        </div>

        <!-- EDIT MODE -->
        <form id="editMode" method="POST" class="hidden mt-4">
            <input type="text" name="name" value="<?= $user['name'] ?>"
                class="w-full px-4 py-3 mb-3 border rounded-lg">

            <input type="text" name="phone" value="<?= $user['phone'] ?>"
                class="w-full px-4 py-3 mb-3 border rounded-lg">

            <input type="password" name="password" placeholder="Change password (optional)"
                class="w-full px-4 py-3 mb-4 border rounded-lg">

            <button type="submit" name="update"
                class="w-full bg-blue-900 text-white py-3 rounded-lg font-semibold hover:bg-blue-800">
                Save Changes
            </button>
        </form>

        <a href="logout.php"
            class="block text-center bg-red-600 mt-4 text-white py-3 rounded-lg font-semibold hover:bg-red-700">
            Logout
        </a>
    </div>

    <!-- ORDERS SECTION -->
    <div class="bg-white rounded-xl shadow-lg p-7 mb-10">
        <h2 class="text-2xl font-bold text-blue-900 mb-6">My Orders</h2>

        <?php if (empty($orders)): ?>

            <p class="text-gray-500 text-center">No orders found.</p>

        <?php else: ?>

            <div class="space-y-5">
                <?php foreach ($orders as $o): ?>

                    <div class="border border-gray-200 p-5 rounded-lg">
                        <div class="flex justify-between">
                            <p class="font-semibold text-gray-700">Order #<?= $o['id'] ?></p>
                            <p class="text-sm text-gray-500"><?= date("d M Y", strtotime($o['created_at'])) ?></p>
                        </div>

                        <p><strong>Amount:</strong> ₹<?= number_format($o['total_amount'], 2) ?></p>

                        <p><strong>Payment:</strong>
                            <?= $o['payment_status'] === 'paid'
                                ? '<span class="text-green-600 font-semibold">Paid</span>'
                                : '<span class="text-red-600 font-semibold">Failed</span>' ?>
                        </p>

                        <p><strong>Shipping Status:</strong>
                            <?= !empty($o['awb_number'])
                                ? '<span class="text-green-600 font-semibold">Shipped</span>'
                                : '<span class="text-gray-500 font-semibold">Pending</span>' ?>
                        </p>

                        <!-- TRACK ORDER BUTTON (simple redirect) -->
                        <a href="https://bluedart.com/tracking"
                           target="_blank"
                           class="block text-center mt-4 bg-blue-900 text-white py-2 rounded-lg hover:bg-blue-800">
                            Track Order →
                        </a>

                    </div>

                <?php endforeach; ?>
            </div>

        <?php endif; ?>
    </div>

</div>

<script>
function toggleEdit() {
    document.getElementById('viewMode').classList.toggle('hidden');
    document.getElementById('editMode').classList.toggle('hidden');
}
</script>

</body>
</html>
