<?php
session_start();
require_once __DIR__ . '/config.php';
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$userid = (int) $_SESSION['user_id'];
$role   = strtolower(trim($_SESSION['role'] ?? 'user'));

/* ROLE LAYOUT */
$layout = [
    'admin'   => ['header' => 'header.php','sidebar' => 'Admin/adminsidebar.php','width'=>260],
    'ra'      => ['header' => 'header.php','sidebar' => 'Ra/rasidebar.php','width'=>260],
    'agency'  => ['header' => 'header.php','sidebar' => 'agency/agencysidebar.php','width'=>260],
    'sales_manager'=>['header'=>'header.php','sidebar'=>'SalesManager/salesmanagersidebar.php','width'=>260],
    'sales_executive'=>['header'=>'header.php','sidebar'=>'salesexecutive/salesexecutivesidebar.php','width'=>260],
    'user'    => ['header'=>'header.php','sidebar'=>'sidebar.php','width'=>260],
];

$conf = $layout[$role] ?? $layout['user'];
$header_file  = $conf['header'];
$sidebar_file = $conf['sidebar'];
$sidebar_width = (int)$conf['width'];

/* CSRF */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

/* FETCH USER */
$stmt = $conn->prepare("SELECT id,name,email,password FROM users WHERE id=?");
$stmt->bind_param("i", $userid);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

$messages=[]; $errors=[];

/* UPDATE PROFILE */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_profile'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[]="Invalid CSRF token";
    } else {
        $name=trim($_POST['name']); 
        $email=trim($_POST['email']);

        if($name==='') $errors[]="Name required";
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)) $errors[]="Valid email required";

        if(empty($errors)){
            $upd=$conn->prepare("UPDATE users SET name=?,email=? WHERE id=?");
            $upd->bind_param("ssi",$name,$email,$userid);
            if($upd->execute()){
                $_SESSION['name']=$name;
                $messages[]="Profile updated";
                $user['name']=$name;
                $user['email']=$email;
            }
        }
    }
}

/* CHANGE PASSWORD */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['change_password'])) {

    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[]="Invalid CSRF token";
    } else {

        $current=$_POST['current_password'];
        $new=$_POST['new_password'];
        $confirm=$_POST['confirm_password'];

        if(!$current || !$new || !$confirm){
            $errors[]="All fields required";
        } elseif($new!==$confirm){
            $errors[]="Passwords do not match";
        } elseif(!password_verify($current,$user['password'])){
            $errors[]="Wrong current password";
        } else {
            $hash=password_hash($new,PASSWORD_DEFAULT);
            $upd=$conn->prepare("UPDATE users SET password=? WHERE id=?");
            $upd->bind_param("si",$hash,$userid);

            if($upd->execute()){
                $messages[]="Password updated";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
:root{ --header-height:65px; }

body{
    margin:0;
    font-family:Arial;
    background:#f1f5f9;
}

.main-content{
    margin-left:<?php echo $sidebar_width;?>px;
    margin-top:var(--header-height);
    padding:30px;
}

/* header */
.profile-header{
    display:flex;
    align-items:center;
    gap:15px;
    margin-bottom:20px;
}

.profile-avatar{
    width:60px;height:60px;
    border-radius:12px;
    background:#2563eb;
    color:#fff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:22px;
    font-weight:bold;
}

/* cards */
.card{
    background:#fff;
    padding:20px;
    border-radius:12px;
    box-shadow:0 10px 25px rgba(0,0,0,0.05);
    border:1px solid #e5e7eb;
}

.row{ display:flex; gap:20px; flex-wrap:wrap; }
.col{ flex:1; min-width:300px; }

label{ font-weight:600; }

input{
    width:100%;
    padding:10px;
    margin-top:5px;
    border-radius:8px;
    border:1px solid #d1d5db;
}

/* buttons */
.btn{
    background:#2563eb;
    color:#fff;
    border:none;
    padding:10px 15px;
    border-radius:8px;
    cursor:pointer;
}
.btn.secondary{ background:#9ca3af; }

/* msg */
.msg{ background:#dcfce7;color:#166534;padding:10px;border-radius:8px;margin-bottom:10px; }
.err{ background:#fee2e2;color:#991b1b;padding:10px;border-radius:8px;margin-bottom:10px; }

</style>
</head>

<body>

<?php include __DIR__ . '/' . $header_file; ?>
<?php include __DIR__ . '/' . $sidebar_file; ?>

<div class="main-content">

<div class="profile-header">
    <div class="profile-avatar">
        <?php echo strtoupper(substr($user['name'],0,1)); ?>
    </div>
    <div>
        <h2>My Profile</h2>
        <small style="color:gray;">Manage your account</small>
    </div>
</div>

<?php foreach($messages as $m): ?><div class="msg"><?php echo $m;?></div><?php endforeach;?>
<?php foreach($errors as $e): ?><div class="err"><?php echo $e;?></div><?php endforeach;?>

<div class="row">

<!-- PROFILE -->
<div class="col card">
<form method="post">
<input type="hidden" name="csrf_token" value="<?php echo $csrf;?>">

<label>Name</label>
<input type="text" name="name" value="<?php echo esc($user['name']);?>">

<label>Email</label>
<input type="email" name="email" value="<?php echo esc($user['email']);?>">

<div style="margin-top:10px;">
<button class="btn" name="update_profile">Save</button>
<button class="btn secondary" type="reset">Reset</button>
</div>

</form>
</div>

<!-- PASSWORD -->
<div class="col card">
<form method="post">
<input type="hidden" name="csrf_token" value="<?php echo $csrf;?>">

<label>Current Password</label>
<input type="password" name="current_password">

<label>New Password</label>
<input type="password" name="new_password">

<label>Confirm Password</label>
<input type="password" name="confirm_password">

<div style="margin-top:10px;">
<button class="btn" name="change_password">Change Password</button>
</div>

</form>
</div>

</div>

</div>

</body>
</html>