<?php
session_start();
if(isset($_SESSION['user_id'])){
    $role = $_SESSION['user_role'] ?? 'customer';
    header('Location: ' . ($role === 'admin' ? '/stile-lpg/admin/index.php' : '/stile-lpg/customer/dashboard.php'));
    exit;
}

$pageTitle  = 'Login';
$currentPage = 'login';
$error = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sign_in'])){
  $email    = strtolower(trim($_POST['email'] ?? ''));
    $password = $_POST['password'] ?? '';

    if(!$email || !$password){
        $error = 'Please enter your email and password.';
    } else {
  require_once __DIR__ . '/backend/config/database.php';
  $db = getDB();
        $stmt = $db->prepare("SELECT id,name,email,password,role FROM users WHERE LOWER(email)=LOWER(?) AND is_active=1");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if($user && password_verify($password, $user['password'])){
            require_once __DIR__ . '/backend/middleware/auth.php';
            $token = jwtCreate(['id'=>$user['id'],'email'=>$user['email'],'name'=>$user['name'],'role'=>$user['role']]);
            $_SESSION['user_id']   = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_email']= $user['email'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['jwt_token'] = $token;
            
            // Check for redirect parameter
            $redirect = $_GET['redirect'] ?? '';
            
            // If there's a redirect parameter, go back to that page
            if($redirect) {
                // Map redirect codes to actual URLs
                $redirectUrls = [
                    'services' => '/stile-lpg/services.php',
                    'accessories' => '/stile-lpg/accessories.php',
                    'contact' => '/stile-lpg/contact.php',
                    'gallery' => '/stile-lpg/gallery.php',
                ];
                
                // If redirect matches a known page, go there
                if(isset($redirectUrls[$redirect])) {
                    header('Location: ' . $redirectUrls[$redirect]);
                } else {
                    // For any other redirect value, treat it as a relative path
                    header('Location: /stile-lpg/' . $redirect);
                }
            }
            // Admin users go to admin dashboard
            elseif($user['role'] === 'admin') {
                header('Location: /stile-lpg/admin/index.php');
            }
            // Regular users go to customer dashboard
            else {
                header('Location: /stile-lpg/customer/dashboard.php');
            }
            exit;
        } else {
            $error = 'Invalid email or password. Please try again.';
        }
    }
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Login — Stiles LPG</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Inter',sans-serif;min-height:100vh;display:flex}
a{text-decoration:none;color:inherit}
input{font-family:inherit;font-size:.9rem;width:100%;padding:.75rem 1rem;border:2px solid #e2e8f0;border-radius:14px;outline:none;transition:border-color .2s,box-shadow .2s;background:#fff;color:#0f172a}
input:focus{border-color:#f97316;box-shadow:0 0 0 3px rgba(249,115,22,.12)}
.btn-primary{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;background:linear-gradient(135deg,#f97316,#fb923c);color:#fff;border:none;padding:.85rem 1.5rem;border-radius:14px;font-weight:800;font-size:.9rem;cursor:pointer;transition:all .2s;width:100%;box-shadow:0 4px 16px rgba(249,115,22,.35)}
.btn-primary:hover{transform:translateY(-1px);box-shadow:0 8px 24px rgba(249,115,22,.5)}
.alert-error{background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:.85rem 1rem;border-radius:12px;font-size:.875rem;font-weight:500}
/* Brand panel */
#login-brand-panel{display:none;flex:1;background:linear-gradient(145deg,#0f172a 0%,#1e293b 40%,#7c2d12 100%);padding:3rem;flex-direction:column;justify-content:space-between;position:relative;overflow:hidden}
@media(min-width:900px){#login-brand-panel{display:flex}}
#login-brand-panel::before{content:'';position:absolute;top:-100px;right:-100px;width:400px;height:400px;background:radial-gradient(circle,rgba(249,115,22,.2) 0%,transparent 70%)}
#login-brand-panel::after{content:'';position:absolute;bottom:-80px;left:-80px;width:300px;height:300px;background:radial-gradient(circle,rgba(124,45,18,.4) 0%,transparent 70%)}
/* Form panel */
#login-form-panel{flex:1;display:flex;flex-direction:column;justify-content:center;padding:3rem;background:#f8f9fb;min-height:100vh;max-width:480px}
@media(max-width:900px){#login-form-panel{max-width:100%;min-height:100vh}}
.demo-btn{background:#f1f5f9;border:1.5px solid #e2e8f0;color:#475569;padding:.6rem 1rem;border-radius:10px;font-size:.78rem;font-weight:700;cursor:pointer;transition:all .15s;font-family:inherit}
.demo-btn:hover{background:#e2e8f0;border-color:#cbd5e1}
</style>
</head>
<body>

<!-- Brand panel (left, desktop) -->
<div id="login-brand-panel">
  <div style="position:relative;z-index:1">
    <a href="/stile-lpg/index.php" style="display:inline-flex;align-items:center;text-decoration:none">
      <div style="display:flex;align-items:center">
        <img src="/stile-lpg/backend/uploads/footer-image.png" alt="Stiles Energy Logo" style="width:140px;height:auto;object-fit:contain">
      </div>
    </a>
  </div>
  <div style="position:relative;z-index:1">
    <div style="display:inline-flex;align-items:center;gap:.5rem;background:rgba(249,115,22,.2);border:1px solid rgba(249,115,22,.35);border-radius:50px;padding:.4rem 1rem;margin-bottom:1.5rem">
      <svg width="12" height="12" fill="none" stroke="#f97316" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13 2 3 14h7l-1 8 10-12h-7z"/></svg>
      <span style="color:#f97316;font-size:.78rem;font-weight:700;letter-spacing:.06em">TRUSTED & CERTIFIED</span>
    </div>
    <h2 style="color:#fff;font-weight:900;font-size:2rem;line-height:1.2;margin-bottom:1rem">Safe Gas,<br>Delivered <span style="background:linear-gradient(90deg,#f97316,#fbbf24);-webkit-background-clip:text;-webkit-text-fill-color:transparent">Fast</span></h2>
    <p style="color:#94a3b8;font-size:.95rem;line-height:1.7;margin-bottom:2rem">Sign in to manage your orders, track deliveries, and enjoy exclusive customer benefits.</p>
    <div style="display:flex;flex-direction:column;gap:.85rem">
      <?php $feats = ['Same-day LPG delivery to your door','DPR certified - 100% safe cylinders','Pay only on delivery - no upfront cost','Trusted by 500+ customers across Nigeria'];
      foreach($feats as $f): ?>
      <div style="display:flex;align-items:center;gap:.75rem">
        <div style="width:20px;height:20px;border-radius:50%;background:linear-gradient(135deg,#22c55e,#16a34a);display:flex;align-items:center;justify-content:center;font-size:10px;color:#fff;flex-shrink:0">✓</div>
        <span style="color:#cbd5e1;font-size:.875rem"><?= $f ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <div style="position:relative;z-index:1;display:flex;gap:2rem">
    <?php $brandStats=[['500+','Customers'],['24/7','Support'],['5+','Years']];
    foreach($brandStats as $bs): ?>
    <div>
      <div style="color:#f97316;font-weight:900;font-size:1.5rem"><?= $bs[0] ?></div>
      <div style="color:#64748b;font-size:.78rem"><?= $bs[1] ?></div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- Form panel (right) -->
<div id="login-form-panel">
  <div style="max-width:380px;width:100%;margin:0 auto">
    <!-- Back link -->
    <a href="/stile-lpg/index.php" style="display:inline-flex;align-items:center;gap:.4rem;color:#64748b;font-size:.85rem;font-weight:600;margin-bottom:2.5rem;transition:color .2s">
      <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m15 18-6-6 6-6"/></svg>
      Back to Home
    </a>

    <!-- Logo -->
    <div style="display:flex;align-items:center;justify-content:center;margin-bottom:2rem">
      <img src="/stile-lpg/backend/uploads/logo1.png" alt="Stiles Energy Logo" style="width:90px;height:auto;object-fit:contain">
    </div>

    <h1 style="color:#0f172a;font-weight:900;font-size:1.6rem;margin-bottom:.35rem">Welcome Back</h1>
    <p style="color:#64748b;font-size:.875rem;margin-bottom:2rem">Sign in to your account to continue</p>

    <?php if($error): ?>
    <div class="alert-error" style="margin-bottom:1.5rem"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div style="background:#fff;border-radius:20px;padding:2rem;box-shadow:0 4px 24px rgba(0,0,0,.07);border:1px solid #f1f5f9">
      <form method="POST" action="/stile-lpg/login.php<?= isset($_GET['redirect']) ? '?redirect='.htmlspecialchars($_GET['redirect']) : '' ?>">
        <div style="margin-bottom:1.1rem">
          <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Email Address</label>
          <input type="email" name="email" id="email_input" required placeholder="you@example.com" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
        </div>
        <div style="margin-bottom:.6rem">
          <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Password</label>
          <div style="position:relative">
            <input type="password" name="password" id="pw_input" required placeholder="••••••••" style="padding-right:3rem">
            <button type="button" onclick="togglePw()" style="position:absolute;right:.9rem;top:50%;transform:translateY(-50%);background:none;border:none;color:#94a3b8;cursor:pointer" id="pw_eye" aria-label="Toggle password visibility">
              <svg id="pw_eye_icon" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>
            </button>
          </div>
        </div>
        <!--<div style="text-align:right;margin-bottom:1.5rem">-->
        <!--  <a href="#" style="color:#f97316;font-size:.78rem;font-weight:700">Forgot password?</a>-->
        <!--</div>-->
        <button type="submit" name="sign_in" value="1" class="btn-primary">
          <svg width="15" height="15" fill="none" stroke="#fff" stroke-width="2" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2"/><path stroke-linecap="round" stroke-linejoin="round" d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
          Sign In
        </button>
      </form>

    </div>

    <p style="text-align:center;color:#64748b;font-size:.875rem;margin-top:1.5rem">
      Don't have an account? <a href="/stile-lpg/register.php" style="color:#f97316;font-weight:700">Create one →</a>
    </p>
  </div>
</div>

<script>
function togglePw(){
  const inp = document.getElementById('pw_input');
  const eye = document.getElementById('pw_eye_icon');
  if(inp.type==='password'){
    inp.type='text';
    eye.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" d="m3 3 18 18"/><path stroke-linecap="round" stroke-linejoin="round" d="M10.58 10.58A2 2 0 0 0 12 14a2 2 0 0 0 1.42-.58"/><path stroke-linecap="round" stroke-linejoin="round" d="M9.88 5.09A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.8 21.8 0 0 1-5.17 5.94M6.71 6.72C3.77 8.64 2 12 2 12s4 7 10 7a10.92 10.92 0 0 0 5.28-1.32"/>';
  } else {
    inp.type='password';
    eye.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/>';
  }
}
</script>
</body>
</html>
