<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']); // cara baru !
} else {
    include "_header.php";
    include "_navtop.php";
    include "_navside.php";
    include "_functions.php";
    require "conn.php";


    $cwallet                = sumWall("masuk", "cwallet") - sumWall("keluar", "cwallet");


    // ------------------------------------------------------
    // Determine which username to use (URL or session)
    // ------------------------------------------------------
    if (isset($_GET['u']) && !empty($_GET['u']) && ($_SESSION['role'] === "admin")) {
        $username = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_GET['u']); // sanitize username from URL
    } else {
        $username = $_SESSION['username'] ?? 'guest';
    }
    
    // ----------------------------------
    // PROCESS FILE UPLOAD
    // ----------------------------------
    if (isset($_POST['uploadImgProfile'])) {
        $targetDir = "uploads/profile/";
        if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);
    
        $targetFile = $targetDir . $username . ".jpg";
        $uploadOk = 1;
    
        // Check if file is an image
        $check = getimagesize($_FILES["profile_image"]["tmp_name"]);
        if ($check === false) {
            $error = "File is not an image.";
            $uploadOk = 0;
        }
    
        // Check file size (2MB max)
        if ($_FILES["profile_image"]["size"] > 2000000) {
            $error = "File too large. Max 2MB allowed.";
            $uploadOk = 0;
        }
    
        // Allow only JPG, JPEG, PNG
        $imageFileType = strtolower(pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION));
        if (!in_array($imageFileType, ['jpg', 'jpeg', 'png'])) {
            $error = "Only JPG, JPEG, and PNG allowed.";
            $uploadOk = 0;
        }
    
        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $targetFile)) {
                $_SESSION['photo'] = $username . ".jpg";
                $success = "Profile image updated successfully!";
            } else {
                $error = "Failed to upload image.";
            }
        }
        
        if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
                       
                                    mysqli_query($con, "UPDATE merchant SET photo='$targetFile'WHERE username='".$username."'");
                       
        }   else    {
                        
                                    mysqli_query($con, "UPDATE ahli SET photo='$targetFile' WHERE username='".$username."'");
                           
        }
    }
    
    
    // ----------------------------------
    // DETERMINE CURRENT IMAGE
    // ----------------------------------
    $userImage = "uploads/profile/{$username}.jpg";
    $defaultImage = "assets/img/find_user.png";
    
    if (!empty($_SESSION['photo']) && file_exists($userImage)) {
        $imgSrc = $userImage . "?v=" . time(); // force refresh
    } else {
        $imgSrc = $defaultImage;
    }
    
    if (isset($_POST['update'])) {

      $password     = mysqli_real_escape_string($con, $_POST['xx']);  
      $nama         = mysqli_real_escape_string($con, $_POST['aa']);
      // $kp           = mysqli_real_escape_string($con, $_POST['bb']);
      $telefon      = mysqli_real_escape_string($con, $_POST['cc']);
      $email        = mysqli_real_escape_string($con, $_POST['dd']);
      $alamat       = mysqli_real_escape_string($con, $_POST['ee']);
      $bandar       = mysqli_real_escape_string($con, $_POST['ff']);
      $poskod       = mysqli_real_escape_string($con, $_POST['gg']);
      $negeri       = mysqli_real_escape_string($con, $_POST['hh']);
      $bank         = mysqli_real_escape_string($con, $_POST['ii']);
      $noakaun      = mysqli_real_escape_string($con, $_POST['jj']);
      $naakaun      = mysqli_real_escape_string($con, $_POST['kk']);
      $bnama        = mysqli_real_escape_string($con, $_POST['ll']);
      $bkp          = mysqli_real_escape_string($con, $_POST['mm']);
      $brelation    = mysqli_real_escape_string($con, $_POST['nn']);
      $BPacc_no     = mysqli_real_escape_string($con, $_POST['bp_acc_no']);
      $BPacc_name   = mysqli_real_escape_string($con, $_POST['bp_acc_name']);

    if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
                    if (empty($password)) {
                                mysqli_query($con, "UPDATE merchant SET nama='$nama', alamat='$alamat', bandar='$bandar', poskod='$poskod', negeri='$negeri', telefon='$telefon', email='$email', bank='$bank', naakaun='$naakaun', noakaun='$noakaun', bnama='$bnama', bkp='$bkp', brelation='$brelation', bp_acc_no ='$BPacc_no', bp_acc_name ='$BPacc_name' WHERE username='".$username."'");
                    } else {
                                mysqli_query($con, "UPDATE merchant SET nama='$nama', alamat='$alamat', bandar='$bandar', poskod='$poskod', negeri='$negeri', telefon='$telefon', email='$email', password='$password', bank='$bank', naakaun='$naakaun', noakaun='$noakaun', bnama='$bnama', bkp='$bkp', brelation='$brelation', bp_acc_no ='$BPacc_no', bp_acc_name ='$BPacc_name' WHERE username='".$username."'");
                    }
    }   else    {
                    if (empty($password)) {
                                mysqli_query($con, "UPDATE ahli SET nama='$nama', alamat='$alamat', bandar='$bandar', poskod='$poskod', negeri='$negeri', telefon='$telefon', email='$email', bank='$bank', naakaun='$naakaun', noakaun='$noakaun', bnama='$bnama', bkp='$bkp', brelation='$brelation', bp_acc_no ='$BPacc_no', bp_acc_name ='$BPacc_name' WHERE username='".$username."'");
                    } else {
                                mysqli_query($con, "UPDATE ahli SET nama='$nama', alamat='$alamat', bandar='$bandar', poskod='$poskod', negeri='$negeri', telefon='$telefon', email='$email', password='$password', bank='$bank', naakaun='$naakaun', noakaun='$noakaun', bnama='$bnama', bkp='$bkp', brelation='$brelation', bp_acc_no ='$BPacc_no', bp_acc_name ='$BPacc_name' WHERE username='".$username."'");
                    }        
    }
      
    

    }
        //
    
    
    // ------------------------------------------
    // UPDATE USER STATUS (ADMIN ONLY)
    // ------------------------------------------
    if (isset($_POST['updateUserStatus']) && ($_SESSION['role'] === "admin" || $_SESSION['role'] === "developer")) {

        $user_id     = mysqli_real_escape_string($con, $_POST['user_id']);
        $new_status  = mysqli_real_escape_string($con, $_POST['new_status']);
    
        // Determine table based on role of viewed profile
        if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
            $table = "merchant";
        } else {
            $table = "ahli";
        }
    
        $sql = "UPDATE $table SET status='$new_status' WHERE id='$user_id'";
        mysqli_query($con, $sql);
    
        // Optional Debug Log
        file_put_contents("debug_log.txt", "[".date('Y-m-d H:i:s')."] STATUS UPDATED: ID=$user_id STATUS=$new_status\n", FILE_APPEND);
    
        // Refresh page to show change
        echo "<script>window.location.href='profile.php?u=".$username."';</script>";
        exit;
    }


// Tentukan query ikut role
if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
    $result = mysqli_query($con, "SELECT * FROM merchant WHERE username='" . $username . "'");
} else {
    $result = mysqli_query($con, "SELECT * FROM ahli WHERE username='" . $username . "'");
}

$rows = mysqli_fetch_array($result);

// Disable jika merchant
if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
    $dis = 'disabled="disabled"';
} else {
    $dis = "";
}

// Assign nilai dengan fallback supaya tak keluar warning
$carwash    = isset($rows['carwash']) ? $rows['carwash'] : 0;
$polish     = isset($rows['polish']) ? $rows['polish'] : 0;
$repair     = isset($rows['repair']) ? $rows['repair'] : 0;
$accessories= isset($rows['accessories']) ? $rows['accessories'] : 0;
$insurance  = isset($rows['insurance']) ? $rows['insurance'] : 0;

// Warna & checkbox state
if ($carwash == 1)     { $s1 = "text-primary"; $cb1 = "checked"; } else { $s1 = "text-secondary"; $cb1 = ""; }
if ($polish == 1)      { $s2 = "text-primary"; $cb2 = "checked"; } else { $s2 = "text-secondary"; $cb2 = ""; }
if ($repair == 1)      { $s3 = "text-primary"; $cb3 = "checked"; } else { $s3 = "text-secondary"; $cb3 = ""; }
if ($accessories == 1) { $s4 = "text-primary"; $cb4 = "checked"; } else { $s4 = "text-secondary"; $cb4 = ""; }
if ($insurance == 1)   { $s5 = "text-primary"; $cb5 = "checked"; } else { $s5 = "text-secondary"; $cb5 = ""; }


    
?>
        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>Profile</h2>                          
                    </div>
                </div>
            <hr />

			<div class="row">
                <div class="col-md-12">
                    <!-- Form Elements -->
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            Profile
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
<?php
if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {

?>                   
                                        <div class="text-center align-middle">
                                                <?php
                                                   $PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
                                                    
                                                    //html PNG location prefix
                                                    $PNG_WEB_DIR = 'temp/';
                                                
                                                    include "qrcodes/qrlib.php";    
                                                    
                                                    //ofcourse we need rights to create temp dir
                                                    if (!file_exists($PNG_TEMP_DIR))
                                                        mkdir($PNG_TEMP_DIR);
                                                    
                                                    
                                                    $filename = $PNG_TEMP_DIR.'test.png';
                                                
                                                    $errorCorrectionLevel = 'H';
                                                
                                                    $matrixPointSize = 10;
                                                         $dat   = "https://vip.wepayyourcost.com/?m=".$rows['id']."";   
                                                        // user data
                                                        $filename = $PNG_TEMP_DIR.$rows['id'].'.png';
                                                        QRcode::png($dat, $filename, $errorCorrectionLevel, $matrixPointSize, 10);   
                                                        
                                                ?>
                                                    
                                                    <img style=" border: 1px solid #555;" width="180px" height="auto" src="<?= $PNG_WEB_DIR.basename($filename); ?>" >
                                                                            
                                        <p>
                                            <a href="paysticker.php?id=<?= $rows['id'] ?>" class="btn btn-info" role="button" target="_blank">
                                                <i class="fa-solid fa-printer fa-1x"> </i>  Print QRcode Sticker 
                                            </a>  
                                        </p>
                                        </div>
                                        <hr>
<?php
        } 
?>
                                    <center>
                                        <div style="position: relative; display: inline-block;">
                                            <?php
                                               
                                                // Define image path
                                                $userImage = "uploads/profile/{$username}.jpg";
                                                $defaultImage = "assets/img/find_user.png";
                                                
                                                if (!empty($rows['photo']) && file_exists($userImage)) {
                                                    $imgSrc = $userImage . "?v=" . time(); // force refresh
                                                } else {
                                                    $imgSrc = $defaultImage;
                                                }
                                            ?>
                                        
                                            <!-- Profile Image -->
                                            <img src="<?= htmlspecialchars($imgSrc) ?>" 
                                                 class="user-image img-responsive" 
                                                 style="width:200px; height:200px; object-fit:cover; border-radius:50%; border:2px solid #ddd;" 
                                                 alt="User profile image" />
                                        
                                            <!-- Camera Icon Button -->
                                            <button type="button" class="btn btn-dark btn-sm" 
                                                    style="position:absolute; top:8px; right:8px; border-radius:50%; padding:6px 8px;"
                                                    data-toggle="modal" data-target="#uploadModal">
                                                <i class="fa fa-camera"></i>
                                            </button>
                                        </div>
                                        
                                    </center>
                                    <!-- Modal -->
                                    <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
                                      <div class="modal-dialog modal-dialog-centered" role="document">
                                        <div class="modal-content">
                                          
                                          <div class="modal-header">
                                            <h5 class="modal-title" id="uploadModalLabel"><i class="fa fa-camera"></i> Upload Profile Picture</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                              <span>&times;</span>
                                            </button>
                                          </div>
                                    
                                          <form method="POST" enctype="multipart/form-data">
                                            <div class="modal-body text-center">
                                              <input type="file" name="profile_image" accept="image/*" class="form-control mb-3" required>
                                              <small class="text-muted">Accepted formats: JPG, PNG (Max 2MB)</small>
                                            </div>
                                            <div class="modal-footer">
                                              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                              <button type="submit" name="uploadImgProfile" class="btn btn-primary">Upload</button>
                                            </div>
                                          </form>
                                    
                                        </div>
                                      </div>
                                    </div>

                                </div> 
                                <div class="col-md-6">
                                                <div class="col-md-12 col-sm-12 col-xs-12">
                                                    <div class="panel panel-primary text-center no-boder " style="color:white; background-color: #626BCB;">
                                                        <div class="panel-body">
                                                            <h1><?= $rows['pakej'] ?></h1>
                                                        </div>
                                                        <div class="panel-footer " style="color:white; background-color: #3842A8;">
                                                            
    <?php                                                   if ( empty($rows['status']) ) { 
                                                                        echo "INACTIVE"; 
                                                            }   else    {
                                                                        echo strtoupper($rows['status']); 
                                                            }
                                                            
                                                            if ($_SESSION['role'] === "admin" ) { 
    ?>
                                                                <button type="button" class="btn btn-dark btn-sm" 
                                                                        style="color: black; border-radius:50%; margin-left:10px;"
                                                                        data-toggle="modal" data-target="#statusModal<?= $rows['id'] ?>">
                                                                    <i class="fa fa-pen"></i>
                                                                </button>
    <?php                                                   } ?>
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- STATUS MODAL -->
                                                <div class="modal fade" id="statusModal<?= $rows['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="statusModalLabel" aria-hidden="true">
                                                  <div class="modal-dialog modal-dialog-centered" role="document">
                                                    <div class="modal-content">
                                                
                                                      <div class="modal-header">
                                                        <h5 class="modal-title" id="statusModalLabel">
                                                          <i class="fa fa-pen"></i> Change User Status
                                                        </h5>
<?php
if ($_SESSION['role'] === "admin" || $_SESSION['role'] === "developer") {
?>
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                          <span>&times;</span>
                                                        </button>
<?php } ?>                                                        
                                                      </div>
                                                
                                                      <form method="POST" role="form">
                                                        <div class="modal-body text-center">
                                                          <input type="hidden" name="user_id" value="<?= $rows['id'] ?>">
                                                
                                                            <div class="form-group">
                                                                <label for="new_status_<?= $rows['id'] ?>">Select New Status:</label>
                                                                <select name="new_status" id="new_status_<?= $rows['id'] ?>" class="form-control" required>
                                                                    <option value="active"   <?= ($rows['status'] === 'active') ? 'selected' : '' ?>>Active</option>
                                                                    <option value="inactive" <?= ($rows['status'] === 'inactive') ? 'selected' : '' ?>>Inactive</option>
                                                                    <option value="suspend" <?= ($rows['status'] === 'suspend') ? 'selected' : '' ?>>Suspended</option>
                                                                </select>
                                                            </div>
    
                                                        </div>
                                                
                                                        <div class="modal-footer">
                                                          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                                          <button type="submit" name="updateUserStatus" class="btn btn-primary">Update</button>
                                                        </div>
                                                      </form>
                                                
                                                    </div>
                                                  </div>
                                                </div>
                                </div>
                                
                                <form role="form" method="post" class="col-md-12">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Username</label>
                                            <input class="form-control" value="<?= $rows['username'] ?>" readonly />
                                        </div>
                                        <div class="form-group">
                                            <label>Password</label>
                                            <input class="form-control" type="password" name="xx" />
                                            <p class="help-block">leave it blank if you want to keep the current password</p>
                                        </div>                                    
                                        <hr>
                                        <h3>Biodata</h3>
                                        <div class="form-group">
                                            <label>Name</label>
                                            <input class="form-control" placeholder="Full Name" name="aa" value="<?= $rows['nama'] ?>"  />
                                        </div>
<?php
if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
?>
                                        <div class="form-group">
                                            <label>R.O.C</label>
                                            <input class="form-control" value="<?= $rows['roc'] ?>" readonly />
                                        </div>
<?php
    }   else    {
?>
                                        <div class="form-group">
                                            <label>MyKad</label>
                                            <input class="form-control" value="<?= $rows['kp'] ?>" readonly />
                                        </div>
<?php
        }
?>                                                                              
                                        <div class="form-group">
                                            <label>Phone</label>
                                            <input class="form-control" placeholder="your mobile phone no." name="cc" value="<?= $rows['telefon'] ?>" />
                                        </div>
                                        <div class="form-group">
                                            <label>Email</label>
                                            <input class="form-control" type="email" placeholder="valid email only" name="dd" value="<?= $rows['email'] ?>" />
                                        </div>
                                        <div class="form-group">
                                            <label>Address</label>
                                            <input class="form-control" placeholder="without city, postcode, state" name="ee" value="<?= $rows['alamat'] ?>" />
                                        </div>
                                        <div class="form-group">
                                            <label>City</label>
                                            <input class="form-control" name="ff" value="<?= $rows['bandar'] ?>" />
                                        </div>
                                        <div class="form-group">
                                            <label>Postcode</label>
                                            <input class="form-control" name="gg" value="<?= $rows['poskod'] ?>" />
                                        </div>                                                                                
                                        <div class="form-group">
                                            <label>State</label>
                                            <input class="form-control" name="hh" value="<?= $rows['negeri'] ?>" />
                                        </div>
                                    </div>
                                
                                    <div class="col-md-6">
    <?php           
    if (isset($_SESSION['role']) && $_SESSION['role'] === "merchant") {
    ?>
                                        <div class="form-group">
                                        <h3>Services</h3>
                                           
                                                <div class="form-group" style="padding:10px; text-align: center;">
                                                    <input type="checkbox" id="carwash"     name="carwash"      <?= $cb1." ".$dis ?> >       <label style="padding-right:20px;" for="carwash">       <i class="<?= $s1 ?> fa fa-tint fa-2x"                  title="Carwash"></i></label>
                                                    <input type="checkbox" id="polish"      name="polish "      <?= $cb2." ".$dis ?> >       <label style="padding-right:20px;" for="polish">        <i class="<?= $s2 ?> fa fa-star-half-stroke fa-2x"      title="Polish"></i></label>
                                                    <input type="checkbox" id="repair"      name="repair "      <?= $cb3." ".$dis ?> >       <label style="padding-right:20px;" for="repair">        <i class="<?= $s3 ?> fa fa-wrench fa-2x"                title="Repair"></i></label>
                                                    <input type="checkbox" id="accessories" name="accessories"  <?= $cb4." ".$dis ?> >       <label style="padding-right:20px;" for="accessories">   <i class="<?= $s4 ?> fa fa-magic fa-2x"                 title="Accessories"></i></label>
                                                    <input type="checkbox" id="insurance"   name="insurance"    <?= $cb5." ".$dis ?> >       <label style="padding-right:20px;" for="insurance">     <i class="<?= $s5 ?> fa fa-shield fa-2x"                title="Insurance"></i></label>
                                                </div>
                                 
                                        </div>
                                        <hr>
    <?php
        }
    ?>
                                        <h3><img src="bigpay.png" style="width:100px; height:auto;" /> Details</h3>
                                            <div class="form-group">
                                                
                                            </div>
                                            <div class="form-group">
                                                <label>Account No.</label>
                                                <input class="form-control" placeholder="BigPAY account no." name="bp_acc_no" value="<?= $rows['bp_acc_no'] ?>" />
                                            </div>                                        
                                            <div class="form-group">
                                                <label>Account Name</label>
                                                <input class="form-control" placeholder="BigPAY account name" name="bp_acc_name" value="<?= $rows['bp_acc_name'] ?>" />
                                            </div>
                                        <hr>
                                        <h3>Bank Details</h3>
                                            <div class="form-group">
                                                <label>Bank Name</label>
                                                <input class="form-control" name="ii" value="<?= $rows['bank'] ?>" />
                                            </div>
                                            <div class="form-group">
                                                <label>Account No.</label>
                                                <input class="form-control" placeholder="bank account no." name="jj" value="<?= $rows['noakaun'] ?>" />
                                            </div>                                        
                                            <div class="form-group">
                                                <label>Account Name</label>
                                                <input class="form-control" placeholder="your mobile phone no." name="kk" value="<?= $rows['naakaun'] ?>" />
                                            </div>
                                        <hr>
                                        <h3>Beneficiary</h3>
                                            <div class="form-group">
                                                <label>Full Name</label>
                                                <input class="form-control" placeholder="" name="ll" value="<?= $rows['bnama'] ?>" />
                                            </div>
                                            <div class="form-group">
                                                <label>MyKad</label>
                                                <input class="form-control" placeholder="your beneficiary MyKad no." name="mm" value="<?= $rows['bkp'] ?>" />
                                            </div>                                        
                                            <div class="form-group">
                                                <label>Relationship</label>
    <?
    $a = $b = $c = $d = "";
    $s = " selected";
    switch ($rows['brelation']) {
    
        case "p":
        $a = $s;
        break;
    
        case "s":
        $b = $s;
        break;
    
        case "c":
        $c = $s;
        break;
    
        case "o":
        $d = $s;
        break;
    
        default:
        $d = $s;
    }
    ?>                                            
                                                <select class="form-control" name="nn">
                                                    <option<?= $a ?> value="p">Parent</option>
                                                    <option<?= $b ?> value="s">Spouse</option>
                                                    <option<?= $c ?> value="c">Children</option>
                                                    <option<?= $d ?> value="o">Others</option>
                                                </select>
                                            </div>
                                            <button type="submit" name="update" class="btn btn-primary">Update</button>
    
                                       
    
                                    </div>   
                                </form>                              
                            </div>
                        </div>
                    </div>
                     <!-- End Form Elements -->
                </div>

			</div>


             <!-- /. PAGE INNER  -->
<? kaki: ?>			 
            </div>
         <!-- /. PAGE WRAPPER  -->
        </div>
<?
    include "_footer.php";
}
?>
