<?php
include("inc/header.php");

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] != 'admin') {
    echo "<script>window.location.href='index.php';</script>";
    exit;
}

$admin_id = $_SESSION['user_id'];

$res = mysqli_query($conn, "SELECT * FROM tbl_register WHERE id='$admin_id'");
$admin = mysqli_fetch_assoc($res);

$name    = $admin['name'];
$email   = $admin['email'];
$phone   = $admin['phone'];
$profile = $admin['profile_image'];
$created = $admin['created_date'];

/* ================= UPDATE ================= */
if(isset($_POST['update_profile'])){

    $name  = mysqli_real_escape_string($conn,$_POST['name']);
    $email = mysqli_real_escape_string($conn,$_POST['email']);
    $phone = mysqli_real_escape_string($conn,$_POST['phone']);
    $pass  = mysqli_real_escape_string($conn,$_POST['password']);

    $old_image = $_POST['old_image'];
    $image = $old_image;

    if (!preg_match('/^\+\d{4}-\d{3}-\d{3}$/', $phone)) {
    $_SESSION['error'] = "Invalid phone format. Use +0000-001-658";
    echo "<script>window.location.href='';</script>";
    exit;
}

    if(!empty($_FILES['profile_image']['name'])){

        $img = time().'_'.$_FILES['profile_image']['name'];
        move_uploaded_file($_FILES['profile_image']['tmp_name'],"uploads/".$img);

        $image = $img;
    }

    if(!empty($pass)){
        $hash = md5($pass);

        mysqli_query($conn,"UPDATE tbl_register SET 
            name='$name',
            email='$email',
            phone='$phone',
            password='$hash',
            profile_image='$image'
            WHERE id='$admin_id'
        ");
    } else {

        mysqli_query($conn,"UPDATE tbl_register SET 
            name='$name',
            email='$email',
            phone='$phone',
            profile_image='$image'
            WHERE id='$admin_id'
        ");
    }

    $_SESSION['success'] = "Profile Updated Successfully";
    echo "<script>window.location.href='';</script>";
    exit;
}
?>

<style>
body{
    background:#f6f7f9;
}

/* MAIN WRAPPER */
.profile-card-wrapper{
    max-width:1000px;
    margin:auto;
    display:flex;
    gap:25px;
}

/* LEFT */
.profile-left{
    width:30%;
    background:#fff;
    border-radius:16px;
    padding:25px;
    text-align:center;
    box-shadow:0 10px 25px rgba(0,0,0,0.05);
}

.profile-img-box{
    position:relative;
    display:inline-block;
}

.profile-img-box img{
    width:140px;
    height:140px;
    border-radius:50%;
    object-fit:cover;
    border:4px solid #eee;
}

/* CAMERA ICON */
.camera-icon{
    position:absolute;
    bottom:8px;
    right:8px;
    width:38px;
    height:38px;
    background:#111;
    color:#fff;
    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;
    cursor:pointer;
    border:2px solid #fff;
    transition:0.3s;
}

.camera-icon:hover{
    background:#000;
    transform:scale(1.05);
}

.profile-left h4{
    margin-top:15px;
    font-weight:600;
}

/* RIGHT */
.profile-right{
    width:70%;
    background:#fff;
    border-radius:16px;
    padding:30px;
    box-shadow:0 10px 25px rgba(0,0,0,0.05);
}

.section-title{
    font-size:18px;
    font-weight:600;
    margin-bottom:20px;
    color:#111;
}

.form-control{
    height:45px;
    border-radius:10px;
}

.btn-save{
    background:#111;
    color:#fff;
    padding:10px 25px;
    border-radius:10px;
    border:none;
    transition:0.3s;
}

.btn-save:hover{
    background: #f21b25;
}
</style>

<div class="container my-5">

    <div class="profile-card-wrapper">

        <!-- LEFT SIDE -->
        <div class="profile-left">

            <div class="profile-img-box">

                <img id="previewImg"
                     src="<?php echo !empty($profile) ? 'uploads/'.$profile : 'https://i.pravatar.cc/150'; ?>">

                <label for="imgInput" class="camera-icon">
                    <i class="fas fa-camera"></i>
                </label>

                <input type="file"
                       name="profile_image"
                       id="imgInput"
                       form="profileForm"
                       hidden>

            </div>

            <h4><?php echo $name; ?></h4>
            <small class="text-muted">Administrator</small>

        </div>

        <!-- RIGHT SIDE -->
        <div class="profile-right">

            <div class="section-title">Admin Profile Settings</div>

            <form method="POST" enctype="multipart/form-data" id="profileForm">

                <input type="hidden" name="old_image" value="<?php echo $profile; ?>">

                <div class="row">

                    <div class="col-md-6 mb-3">
                        <label>Name</label>
                        <input type="text" name="name" class="form-control" value="<?php echo $name; ?>">
                    </div>

                    <div class="col-md-6 mb-3">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control" value="<?php echo $email; ?>">
                    </div>

                    <div class="col-md-6 mb-3">
    <label>Phone</label>
    <input type="text" 
           name="phone" 
           class="form-control"
           value="<?php echo $phone; ?>"
           placeholder="+0000-001-658"
           maxlength="13"
           required>
    <small class="text-muted">Format: +0000-001-658</small>
</div>

                    <div class="col-md-6 mb-3">
                        <label>New Password</label>
                        <input type="password" name="password" class="form-control" placeholder="Leave empty if not changing">
                    </div>

                </div>

                <button type="submit" name="update_profile" class="btn-save">
                    Update Profile
                </button>

            </form>

        </div>

    </div>

</div>

<?php include("inc/footer.php"); ?>
   <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php if(isset($_SESSION['success'])){ ?>
<script>
    toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "3000"
};
toastr.success("<?php echo $_SESSION['success']; ?>");
</script>
<?php unset($_SESSION['success']); } ?>

<?php if(isset($_SESSION['error'])){ ?>
<script>
toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "3000"
};

toastr.error("<?php echo $_SESSION['error']; ?>");
</script>
<?php unset($_SESSION['error']); } ?>

<script>
document.getElementById('imgInput').addEventListener('change', function(e){
    const reader = new FileReader();
    reader.onload = function(){
        document.getElementById('previewImg').src = reader.result;
    }
    reader.readAsDataURL(e.target.files[0]);
});

document.querySelector('input[name="phone"]').addEventListener('input', function (e) {

    let val = e.target.value;

    // remove everything except numbers and +
    val = val.replace(/[^\d+]/g, '');

    // ensure only one +
    if (val.indexOf('+') > 0) {
        val = val.replace(/\+/g, '');
    }

    if (!val.startsWith('+')) {
        val = '+' + val;
    }

    // remove + for formatting
    let numbers = val.substring(1);

    // limit max 10 digits
    numbers = numbers.substring(0, 10);

    let formatted = '+';

    if (numbers.length > 0) {
        formatted += numbers.substring(0, 4);
    }
    if (numbers.length > 4) {
        formatted += '-' + numbers.substring(4, 7);
    }
    if (numbers.length > 7) {
        formatted += '-' + numbers.substring(7, 10);
    }

    e.target.value = formatted;
});
</script>
