<?php
include( 'inc/template.php' );
if (!isset($_SESSION['Role']) || $_SESSION['Role'] !== 'Admin') {
    // Show an alert if the user is not an employee
    echo "<script>alert('You do not have access to this page.'); window.location.href = 'login.php';</script>";
    exit(); // Stop further execution of the page
}
?>

<div class="container-fluid flex-grow-1 container-p-y">
	<h4 class="py-1 mb-1"><span class="text-muted fw-light">My Profile</h4>
	<div class="row mb-4">
		
		<div class="col-xl-12 col-lg-6 col-md-6 mb-3">
			<div class="card">
			
		        	<form class="card-body" id="doctorprofile" method="post" enctype="multipart/form-data">
				
				<div class="row g-3">
					<div class="col-md-6">
						<label class="form-label" for="multicol-username">Name</label>
						<input type="text" id="FullName" name="FullName" class="form-control"  required/>

					</div>
					<div class="col-md-6">
						<label class="form-label" for="multicol-email">Contact No.</label>
						<input type="tel" id="Mobile" name="Mobile" class="form-control" pattern="\d{10}" maxlength="10" inputmode="numeric" oninput="this.value=this.value.replace(/[^0-9]/g,'');"  required/>
					</div>
					<div class="col-md-6">
						<label class="form-label" for="multicol-username">Email</label>
						<input type="email" id="Email" name="Email" class="form-control"  required/>
					</div>
					<div class="col-md-6">
						<label class="form-label" for="multicol-username">Address</label>
						<textarea id="Address" name="Address" class="form-control"></textarea>
					</div>
					<div class="col-md-6">
						<label class="form-label" for="multicol-username">Location</label>
						<input type="text" id="Location" name="Location" class="form-control" />
					</div>
					<div class="col-md-6">
						<label class="form-label" for="multicol-username">Clinic Name</label>
						<input type="text" id="ClinicName" name="ClinicName" class="form-control" />
					</div>
					
					<div class="col-md-6">
						<label class="form-label" for="multicol-email">Message</label>
                        <textarea id="Message" name="Message"  class="form-control"></textarea>
					
					</div>
					
					<div class="col-md-6">
						<label class="form-label" for="multicol-email">Username</label>

						<input type="text" id="username" name="username" class="form-control" 
                    oninput="this.value = this.value.replace(/\s/g, '');" placeholder="Enter Username" maxlength="20" required />

					</div>
					
					
					

					<div class="col-md-6">
						<label class="form-label" for="multicol-email">Company Logo</label>

						 <input  type="file"  name="CompanyLogo" id="CompanyLogo" class="form-control" accept="image/png, image/jpeg, image/jpg" onchange="loadFile(event)"  />
							<script>
  														var loadFile = function(event) {
    													var output = document.getElementById('output');
    													output.src = URL.createObjectURL(event.target.files[0]);
    													output.onload = function() {
      													URL.revokeObjectURL(output.src) // free memory
    													}
  														};
													</script>								

					</div>
					<div class="col-md-6">
						

						<img id="output" src="" height="100" width="250"  />
														

					</div>
					

				</div>
				
				
				
				
				
				<div class="pt-4">
					<input type="hidden" id="upd" value="<?php echo $UserId; ?>">
					<input type="hidden" name="id" id="id">
          <input type="hidden" name="action" id="action" value="Update">
          <button type="submit" class="btn btn-primary me-2"> Update Profile </button>
				
				</div>
			</form>
			
				
			</div>
		</div>
	</div>



</div>
<script>
$(document).ready(function () {
    // Handle form submission
    $('form#doctorprofile').on('submit', function (event) {
        event.preventDefault(); // Prevent default form submission

        // Collect form data
        var formData = {
            FullName: $('#FullName').val(),
            Mobile: $('#Mobile').val(),
            Email: $('#Email').val(),
            Address: $('#Address').val(),
            Location: $('#Location').val(),
            ClinicName: $('#ClinicName').val(),
            Message: $('#Message').val(),
            username: $('#username').val(),
            id: $('#id').val(),
            action: $('#action').val(),
        };

        // Validate required fields
        if (!formData.FullName || !formData.Mobile || !formData.Email || !formData.username) {
            toastr.error('Name, Phone, and Email are required.');
            return;
        }

        // Create a FormData object to handle file uploads
        var formDataObj = new FormData();
        for (const key in formData) {
            formDataObj.append(key, formData[key]);
        }

        // Append file if provided
        var CompanyLogo = $('#CompanyLogo').prop('files')[0];
        if (CompanyLogo) {
            formDataObj.append('CompanyLogo', CompanyLogo);
        }

        // AJAX request
        $.ajax({
            url: 'admin_action.php', // Adjust to your server endpoint
            method: 'POST',
            data: formDataObj,
            contentType: false, // Needed for FormData
            processData: false, // Prevent jQuery from automatically processing data
            success: function (response) {
                try {
                    // Parse response
                    var res = typeof response === 'string' ? JSON.parse(response) : response;

                    // Handle different statuses
                     if (res.status === 'Update') {
                        toastr.success('Record updated successfully.');
                        // setTimeout(function () {
                        //     window.location.href = 'my_profile.php'; // Redirect after success
                        // }, 1500);
                    } else if (res.status === 'Duplicate') {
                        toastr.error('Duplicate entry: Phone or Email already exists.');
                    } else if (res.status === 'Error') {
                        toastr.error('Error: ' + (res.message || 'Unknown error occurred.'));
                    } else {
                        toastr.error('Unexpected response status: ' + res.status);
                    }
                } catch (e) {
                    toastr.error('Error parsing server response.');
                    console.error('Parsing error:', e, 'Response:', response);
                }
            },
            error: function (xhr) {
                toastr.error('An error occurred while submitting the form.');
                console.error('AJAX error:', xhr.responseText);
            },
        });
    });

    // Load form data for updating if `upd` parameter exists
    var upd = $('#upd').val();
    if (upd) {
        $.ajax({
            url: 'admin_action.php', // Adjust to your server endpoint
            method: 'POST',
            data: { id: upd, action: 'Select' },
            dataType: 'json',
            success: function (data) {
                // Populate form fields
                 $('#FullName').val(data.FullName);
                $('#Mobile').val(data.Mobile);
                $('#Email').val(data.Email);
                $('#Address').val(data.Address);
                $('#Location').val(data.Location);
                $('#ClinicName').val(data.ClinicName);
                $('#Message').val(data.Message);
                $('#username').val(data.Username);
                $('#id').val(upd);
                $('#action').val('Update');

                // Show existing profile photo if available
                if (data.CompanyLogo) {
                    $('#output').attr('src', data.CompanyLogo).show();
                } else {
                    $('#output').attr('src', '').hide();
                }
            },
            error: function () {
                toastr.error('Error fetching data for update.');
            },
        });
    }

    // Image preview
    $('#CompanyLogo').on('change', function (event) {
        var output = $('#output');
        var file = event.target.files[0];
        if (file) {
            output.attr('src', URL.createObjectURL(file)).show();
            output.on('load', function () {
                URL.revokeObjectURL(output.attr('src')); // Free memory
            });
        } else {
            output.attr('src', '').hide();
        }
    });
});

</script>

<?php include('inc/footer.php');?>