<?php
session_start();
include 'db_config.php';
include 'functions.php';

$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $phone = sanitize_input($_POST['phone']);
    $full_name = sanitize_input($_POST['full_name']);
    $password = $_POST['password'];
    
    // Simple Sri Lankan phone number validation (starts with 07 and 10 digits)
    if (preg_match('/^07[0,1,2,4,5,6,7,8][0-9]{7}$/', $phone)) {
        if(empty($full_name)) {
            $error = "Please enter your full name.";
        } elseif(empty($password)) {
            $error = "Please enter a password.";
        } else {
            // Check if customer exists
            $stmt = $conn->prepare("SELECT id, password FROM customers WHERE phone = ?");
            $stmt->bind_param("s", $phone);
            $stmt->execute();
            $res = $stmt->get_result();
            
            if ($res->num_rows > 0) {
                $customer = $res->fetch_assoc();
                $customer_id = $customer['id'];
                
                // If user has no password (legacy account), set the provided password as their new password
                if (empty($customer['password'])) {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt_upd = $conn->prepare("UPDATE customers SET full_name = ?, password = ? WHERE id = ?");
                    $stmt_upd->bind_param("ssi", $full_name, $hashed_password, $customer_id);
                    $stmt_upd->execute();
                    $stmt_upd->close();
                } else {
                    // Verify password
                    if (!password_verify($password, $customer['password'])) {
                        $error = "Incorrect password.";
                    } else {
                        // Update name if changed
                        $stmt_upd = $conn->prepare("UPDATE customers SET full_name = ? WHERE id = ?");
                        $stmt_upd->bind_param("si", $full_name, $customer_id);
                        $stmt_upd->execute();
                        $stmt_upd->close();
                    }
                }
            } else {
                // Create new customer
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt_ins = $conn->prepare("INSERT INTO customers (phone, full_name, password) VALUES (?, ?, ?)");
                $stmt_ins->bind_param("sss", $phone, $full_name, $hashed_password);
                $stmt_ins->execute();
                $customer_id = $stmt_ins->insert_id;
                $stmt_ins->close();
            }
            $stmt->close();
            
            if (empty($error)) {
                // Log in
                $_SESSION['customer_id'] = $customer_id;
                $_SESSION['customer_phone'] = $phone;
                $_SESSION['customer_name'] = $full_name;
                $_SESSION['role'] = 'customer';
                
                // Always log in (set long-lived cookie)
                setcookie('customer_login', $phone, time() + (86400 * 365), "/"); // 1 year
                
                header("Location: customer_dashboard.php");
                exit();
            }
        }
    } else {
        $error = "Please enter a valid Sri Lankan phone number (e.g. 0771234567)";
    }
}

// Check if already logged in via cookie
if (!isset($_SESSION['customer_id']) && isset($_COOKIE['customer_login'])) {
    $phone = $_COOKIE['customer_login'];
    $stmt = $conn->prepare("SELECT id, full_name FROM customers WHERE phone = ?");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows > 0) {
        $customer = $res->fetch_assoc();
        $_SESSION['customer_id'] = $customer['id'];
        $_SESSION['customer_phone'] = $phone;
        $_SESSION['customer_name'] = $customer['full_name'];
        $_SESSION['role'] = 'customer';
        header("Location: customer_dashboard.php");
        exit();
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Login | Work For Sri Lanka</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .form-input {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(51, 65, 85, 1);
            color: white;
            transition: all 0.3s ease;
        }
        .form-input:focus {
            background: rgba(15, 23, 42, 0.9);
            border-color: #6366f1;
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }
    </style>
</head>
<body class="bg-slate-950 min-h-screen flex items-center justify-center p-4">
    <div class="absolute inset-0 overflow-hidden pointer-events-none">
        <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-600/10 rounded-full blur-[100px] -mt-20 -mr-20"></div>
        <div class="absolute bottom-0 left-0 w-[500px] h-[500px] bg-purple-600/10 rounded-full blur-[100px] -mb-20 -ml-20"></div>
    </div>

    <div class="glass-panel w-full max-w-md p-8 md:p-12 rounded-3xl shadow-2xl relative z-10 text-center">
        <div class="flex justify-center mb-8">
             <a href="<?= BASE_URL ?>/index.php" class="text-3xl font-bold italic tracking-tighter text-white">
                Work For <span class="text-indigo-400">Sri Lanka</span>
            </a>
        </div>
        
        <h3 class="text-2xl font-bold text-white mb-2">Customer Login</h3>
        <p class="text-slate-400 text-sm mb-8">Enter your phone number to find and hire workers.</p>

        <?php if($error): ?>
            <div class="bg-red-500/10 border border-red-500/20 p-4 mb-6 rounded-xl flex items-start text-left">
                <i data-lucide="alert-circle" class="w-5 h-5 text-red-400 mt-0.5 mr-3 flex-shrink-0"></i>
                <p class="text-sm font-medium text-red-400"><?=$error?></p>
            </div>
        <?php endif; ?>

        <form method="post" class="space-y-6">
            <div class="text-left">
                <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-2 ml-1">Full Name</label>
                <div class="relative">
                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500">
                        <i data-lucide="user" class="w-4 h-4"></i>
                    </span>
                    <input type="text" name="full_name" required class="w-full pl-11 pr-4 py-4 rounded-xl form-input outline-none text-lg" placeholder="John Doe">
                </div>
            </div>

            <div class="text-left">
                <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-2 ml-1">Phone Number</label>
                <div class="relative">
                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500">
                        <i data-lucide="phone" class="w-4 h-4"></i>
                    </span>
                    <input type="text" name="phone" required maxlength="10" class="w-full pl-11 pr-4 py-4 rounded-xl form-input outline-none text-lg" placeholder="0771234567">
                </div>
            </div>

            <div class="text-left">
                <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-2 ml-1">Password</label>
                <div class="relative">
                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500">
                        <i data-lucide="lock" class="w-4 h-4"></i>
                    </span>
                    <input type="password" name="password" required class="w-full pl-11 pr-4 py-4 rounded-xl form-input outline-none text-lg" placeholder="••••••••">
                </div>
            </div>

            <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-4 rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-[0.98] flex items-center justify-center gap-2">
                Continue <i data-lucide="arrow-right" class="w-5 h-5"></i>
            </button>
        </form>

        <p class="mt-8 text-slate-500 text-xs">
            By continuing, you agree to our terms of service and privacy policy.
        </p>
    </div>

    <script>
        lucide.createIcons();
    </script>
</body>
</html>
