<?php
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/../backend/config/database.php';

$db     = getDB();
$userId = $_SESSION['user_id'];
$userName = $_SESSION['user_name'];

$success = '';
$error   = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])){
    $name    = trim($_POST['name'] ?? '');
    $phone   = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');

    if(!$name){ $error = 'Name is required.'; }
    else {
        $stmt = $db->prepare("UPDATE users SET name=?,phone=?,address=? WHERE id=?");
        if($stmt->execute([$name,$phone,$address,$userId])){
            $_SESSION['user_name'] = $name;
            $userName = $name;
            $success = 'Profile updated successfully!';
        } else {
            $error = 'Update failed. Please try again.';
        }
    }
}

// Change password
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])){
    $current = $_POST['current_password'] ?? '';
    $new     = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';
    if(!$current || !$new){ $error = 'Please fill all password fields.'; }
    elseif($new !== $confirm){ $error = 'New passwords do not match.'; }
    elseif(strlen($new) < 6){ $error = 'Password must be at least 6 characters.'; }
    else {
        $stmt = $db->prepare("SELECT password FROM users WHERE id=?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!password_verify($current, $user['password'])){ $error = 'Current password is incorrect.'; }
        else {
            $hash = password_hash($new, PASSWORD_BCRYPT);
            $db->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hash,$userId]);
            $success = 'Password changed successfully!';
        }
    }
}

// Load user data
$stmt = $db->prepare("SELECT name,email,phone,address,created_at FROM users WHERE id=?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

$currentPage = 'profile';
$pageTitle   = 'My Profile';
?>
<?php
ob_start();
?>
<style>
.customer-sidebar{width:220px;flex-shrink:0;background:#fff;border-radius:14px;padding:1.25rem .875rem;border:1px solid #e8ecf0;position:sticky;top:80px;align-self:flex-start}
.sidebar-link{display:flex;align-items:center;gap:.75rem;padding:.65rem .875rem;border-radius:8px;color:#64748b;font-weight:500;font-size:.875rem;transition:all .18s;text-decoration:none}
.sidebar-link:hover{background:#f8fafc;color:#0f172a;}
.sidebar-link.active{background:#0f172a;color:#fff;font-weight:600;}
.sidebar-link.active svg{stroke:#f97316;}
.sidebar-link svg{width:16px;height:16px;stroke:currentColor;fill:none;flex-shrink:0;opacity:.7;}
.sidebar-link:hover svg,.sidebar-link.active svg{opacity:1;}
.btn-primary{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;background:#0f172a;color:#fff;border:none;padding:.7rem 1.5rem;border-radius:8px;font-weight:600;font-size:.875rem;cursor:pointer;transition:background .18s}
.btn-primary:hover{background:#1e293b}
input,select{font-family:inherit;font-size:.875rem;width:100%;padding:.7rem .9rem;border:1.5px solid #e2e8f0;border-radius:8px;outline:none;transition:border-color .18s;color:#0f172a}
input:focus,select:focus{border-color:#0f172a}
@media(max-width:900px){.customer-layout{flex-direction:column!important}.customer-sidebar{width:100%!important;position:static!important}}
@media(max-width:600px){.profile-form-grid{grid-template-columns:1fr!important}}
</style>
<?php
$extraStyles = ob_get_clean();
require_once __DIR__ . '/../backend/includes/head.php';
require_once __DIR__ . '/../backend/includes/navbar.php';
echo $extraStyles;
?>

<div style="max-width:1200px;margin:0 auto;padding:2rem 1.5rem;display:flex;gap:2rem;align-items:flex-start" class="customer-layout">
  <aside class="customer-sidebar">
    <div style="text-align:center;padding:.75rem 0 1.25rem;border-bottom:1px solid #f1f5f9;margin-bottom:1rem">
      <div style="width:46px;height:46px;border-radius:10px;background:#0f172a;display:flex;align-items:center;justify-content:center;color:#f97316;font-weight:800;font-size:1.1rem;margin:0 auto .5rem"><?= strtoupper(substr($userName,0,1)) ?></div>
      <div style="font-weight:700;font-size:.875rem;color:#0f172a"><?= htmlspecialchars($userName) ?></div>
      <div style="color:#94a3b8;font-size:.72rem">Customer Account</div>
    </div>
    <nav style="display:flex;flex-direction:column;gap:.125rem">
      <a href="/stile-lpg/customer/dashboard.php" class="sidebar-link">
        <svg viewBox="0 0 24 24" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>
        <span>Dashboard</span>
      </a>
      <a href="/stile-lpg/customer/orders.php" class="sidebar-link">
        <svg viewBox="0 0 24 24" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>
        <span>My Orders</span>
      </a>
      <a href="/stile-lpg/customer/profile.php" class="sidebar-link active">
        <svg viewBox="0 0 24 24" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        <span>Profile</span>
      </a>
    </nav>
  </aside>

  <main style="flex:1;min-width:0">
    <div style="margin-bottom:2rem">
      <h1 style="font-weight:700;font-size:1.375rem;color:#0f172a;margin-bottom:.25rem">My Profile</h1>
      <p style="color:#64748b;font-size:.875rem">Manage your account information</p>
    </div>

    <?php if($success): ?>
    <div style="background:#f0fdf4;border:1px solid #bbf7d0;color:#15803d;padding:.8rem 1.1rem;border-radius:10px;font-size:.875rem;font-weight:500;margin-bottom:1.5rem;display:flex;align-items:center;gap:.5rem"><svg width="16" height="16" fill="none" stroke="#15803d" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> <?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if($error): ?>
    <div style="background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:.8rem 1.1rem;border-radius:10px;font-size:.875rem;font-weight:500;margin-bottom:1.5rem;display:flex;align-items:center;gap:.5rem"><svg width="16" height="16" fill="none" stroke="#dc2626" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- Identity card -->
    <div style="background:linear-gradient(135deg,#0f172a,#1e293b);border-radius:24px;padding:2rem;margin-bottom:2rem;position:relative;overflow:hidden">
      <div style="position:absolute;top:-50px;right:-50px;width:200px;height:200px;background:radial-gradient(circle,rgba(249,115,22,.2) 0%,transparent 70%)"></div>
      <div style="display:flex;align-items:center;gap:1.5rem;position:relative">
        <div style="width:72px;height:72px;border-radius:50%;background:linear-gradient(135deg,#f97316,#fb923c);display:flex;align-items:center;justify-content:center;font-weight:900;font-size:1.75rem;color:#fff;border:3px solid rgba(255,255,255,.15)">
          <?= strtoupper(substr($user['name'],0,1)) ?>
        </div>
        <div>
          <h2 style="color:#fff;font-weight:900;font-size:1.25rem;margin:0 0 .25rem"><?= htmlspecialchars($user['name']) ?></h2>
          <p style="color:#94a3b8;font-size:.875rem;margin:0 0 .5rem"><?= htmlspecialchars($user['email']) ?></p>
          <div style="display:flex;gap:.5rem;flex-wrap:wrap">
            <span style="background:rgba(249,115,22,.2);border:1px solid rgba(249,115,22,.35);color:#fb923c;font-size:.72rem;font-weight:700;padding:.2rem .65rem;border-radius:20px">Customer</span>
            <span style="background:rgba(34,197,94,.15);border:1px solid rgba(34,197,94,.3);color:#4ade80;font-size:.72rem;font-weight:700;padding:.2rem .65rem;border-radius:20px;display:inline-flex;align-items:center;gap:.3rem"><svg width="10" height="10" fill="none" stroke="#4ade80" stroke-width="3" viewBox="0 0 24 24"><polyline stroke-linecap="round" stroke-linejoin="round" points="20 6 9 17 4 12"/></svg> Active</span>
            <span style="color:#64748b;font-size:.72rem;padding:.2rem .65rem">Joined <?= date('M Y', strtotime($user['created_at'])) ?></span>
          </div>
        </div>
      </div>
    </div>

    <!-- Edit form -->
    <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden;margin-bottom:1.5rem">
      <div style="padding:1.5rem;border-bottom:1px solid #f1f5f9">
        <h3 style="font-weight:800;font-size:1rem;color:#0f172a;margin:0">Personal Information</h3>
      </div>
      <form method="POST" style="padding:1.75rem">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1rem" class="profile-form-grid">
          <div>
            <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Full Name *</label>
            <input type="text" name="name" required value="<?= htmlspecialchars($user['name']) ?>">
          </div>
          <div>
            <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Phone</label>
            <input type="tel" name="phone" value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
          </div>
        </div>
        <div style="margin-bottom: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" value="<?= htmlspecialchars($user['email']) ?>" disabled style="background:#f8f9fb;color:#94a3b8;cursor:not-allowed">
        </div>
        <div style="margin-bottom:1.5rem">
          <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Delivery Address</label>
          <input type="text" name="address" placeholder="Your default delivery address" value="<?= htmlspecialchars($user['address'] ?? '') ?>">
        </div>
        <button type="submit" name="update_profile" value="1" class="btn-primary">💾 Save Changes</button>
      </form>
    </div>

    <!-- Change password -->
    <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden">
      <div style="padding:1.5rem;border-bottom:1px solid #f1f5f9">
        <h3 style="font-weight:800;font-size:1rem;color:#0f172a;margin:0">Change Password</h3>
      </div>
      <form method="POST" style="padding:1.75rem">
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;margin-bottom:1.5rem" class="profile-form-grid" style="grid-template-columns:1fr 1fr 1fr">
          <div>
            <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Current Password</label>
            <input type="password" name="current_password" placeholder="••••••••">
          </div>
          <div>
            <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">New Password</label>
            <input type="password" name="new_password" placeholder="Min. 6 chars">
          </div>
          <div>
            <label style="display:block;color:#475569;font-weight:700;font-size:.78rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.5rem">Confirm New</label>
            <input type="password" name="confirm_password" placeholder="Repeat">
          </div>
        </div>
        <button type="submit" name="change_password" value="1" style="background:linear-gradient(135deg,#1e293b,#334155);color:#fff;border:none;padding:.75rem 1.5rem;border-radius:12px;font-weight:700;font-size:.875rem;cursor:pointer;font-family:inherit">🔑 Change Password</button>
      </form>
    </div>
  </main>
</div>
</body>
</html>
