<?php
session_start();
require_once(__DIR__ . '/../includes/db.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: userlogin.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];
$success = $error = "";

/* ================= FETCH USER ================= */
$u = $conn->prepare("SELECT * FROM users WHERE id=?");
$u->bind_param("i", $user_id);
$u->execute();
$user = $u->get_result()->fetch_assoc();

/* ================= UPDATE PROFILE ================= */
if (isset($_POST['update_profile'])) {
    $fullname = trim($_POST['fullname']);
    $email    = trim($_POST['email']);
    $mobile   = trim($_POST['mobile']);

    if ($fullname && $email && $mobile) {
        $up = $conn->prepare("
            UPDATE users SET fullname=?, email=?, mobile=? WHERE id=?
        ");
        $up->bind_param("sssi", $fullname, $email, $mobile, $user_id);
        $up->execute();
        $success = "Profile updated successfully";

        $u->execute();
        $user = $u->get_result()->fetch_assoc();
    } else {
        $error = "All fields are required";
    }
}

/* ================= CHANGE PASSWORD (NO HASH) ================= */
if (isset($_POST['change_password'])) {

    $old = trim($_POST['old_password']);
    $new = trim($_POST['new_password']);
    $confirm = trim($_POST['confirm_password']);

    if ($old !== $user['password']) {
        $error = "Current password is incorrect";
    }
    elseif ($new !== $confirm) {
        $error = "Passwords do not match";
    }
    elseif (!ctype_digit($new)) {
        $error = "Password must be numeric only";
    }
    elseif (strlen($new) < 4) {
        $error = "Password must be at least 4 digits";
    }
    else {
        $p = $conn->prepare("UPDATE users SET password=? WHERE id=?");
        $p->bind_param("si", $new, $user_id);
        $p->execute();

        $success = "Password updated successfully";

        // refresh user data
        $u->execute();
        $user = $u->get_result()->fetch_assoc();
    }
}

/* ================= HOSTING ================= */
$h = $conn->prepare("
    SELECT * FROM hosting_plans 
    WHERE user_id=? AND payment_status='approved'
");
$h->bind_param("i", $user_id);
$h->execute();
$hosting = $h->get_result();

include(__DIR__ . '/../includes/header.php');
include(__DIR__ . '/../includes/navbar.php');
?>

<style>
body{background:#f5f7fb}
.wrapper{max-width:1150px;margin:auto;padding:30px}
.card-box{
    background:#fff;
    border:1px solid #e6e9ef;
    border-radius:14px;
    padding:25px;
    margin-bottom:25px
}
.card-title{
    font-weight:600;
    font-size:17px;
    margin-bottom:20px;
    display:flex;
    justify-content:space-between;
    align-items:center
}
.readonly input{background:#f8f9fc;border:none}
.btn-soft{
    background:#eef2ff;
    color:#0d6efd;
    border:none;
    border-radius:20px;
    padding:6px 16px;
    font-size:14px
}
.badge-active{background:#16a34a}
.badge-expired{background:#dc2626}
.small-muted{font-size:13px;color:#6b7280}
</style>

<div class="wrapper">

<h3 class="fw-semibold mb-4">Account Settings</h3>

<?php if($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif;?>
<?php if($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif;?>

<!-- ================= ACCOUNT ================= -->
<div class="card-box">
<div class="card-title">
    Account Information
    <button class="btn-soft" onclick="enableEdit()">Edit</button>
</div>

<form method="POST" id="profileForm" class="readonly">
<div class="row g-3">

    <div class="col-md-4">
        <label class="small-muted">User ID</label>
        <input class="form-control" value="#<?= $user['id'] ?>" disabled>
    </div>

    <div class="col-md-4">
        <label class="form-label">Password</label>
        <input type="text" class="form-control"
               value="<?= htmlspecialchars($user['password']) ?>" readonly>
    </div>

    <div class="col-md-4">
        <label class="small-muted">Email</label>
        <input name="email" class="form-control" value="<?= $user['email'] ?>" disabled>
    </div>

    <div class="col-md-4">
        <label class="small-muted">Full Name</label>
        <input name="fullname" class="form-control" value="<?= $user['fullname'] ?>" disabled>
    </div>

    <div class="col-md-4">
        <label class="small-muted">Mobile</label>
        <input name="mobile" class="form-control" value="<?= $user['mobile'] ?>" disabled>
    </div>

</div>

<button name="update_profile" class="btn btn-primary mt-3 d-none" id="saveBtn">
    Save Changes
</button>
</form>
</div>

<!-- ================= SECURITY ================= -->
<div class="card-box">
<div class="card-title">Security</div>

<form method="POST" class="row g-3">
    <div class="col-md-4">
        <input type="password" name="old_password" class="form-control" placeholder="Current Password" required>
    </div>
    <div class="col-md-4">
        <input type="password" name="new_password" class="form-control" placeholder="New Numeric Password" required>
    </div>
    <div class="col-md-4">
        <input type="password" name="confirm_password" class="form-control" placeholder="Confirm Password" required>
    </div>

    <div class="col-12 d-flex gap-3 mt-2">
        <button name="change_password" class="btn btn-dark">
            Change Password
        </button>
    </div>
</form>
</div>

<!-- ================= HOSTING ================= -->
<div class="card-box">
<div class="card-title">My Hosting Services</div>

<?php if($hosting->num_rows): ?>
<?php while($p=$hosting->fetch_assoc()):
    $days = floor((strtotime($p['expiry_date']) - time())/86400);
?>
<div class="d-flex justify-content-between align-items-center border rounded p-3 mb-2">
    <div>
        <strong><?= $p['plan_name'] ?></strong><br>
        <span class="small-muted"><?= $p['domain_name'] ?></span>
    </div>
    <span class="badge <?= $days>0?'badge-active':'badge-expired' ?>">
        <?= $days>0 ? "$days days left" : "Expired" ?>
    </span>
</div>
<?php endwhile; ?>
<?php else: ?>
<p class="small-muted">No hosting services found.</p>
<?php endif; ?>
</div>

</div>

<script>
function enableEdit(){
    document.querySelectorAll('#profileForm input').forEach(i=>{
        if(i.name) i.disabled=false;
    });
    document.getElementById('saveBtn').classList.remove('d-none');
}
</script>

<?php
include(__DIR__ . '/../includes/footer.php');
include(__DIR__ . '/../includes/scripts.php');
?>
