<?php


$conn=new MySQLi("localhost","rishtadepot_new","Sailor@#321","rishtadepot_live");

$sql = "SELECT * FROM caste";
$caste_result = mysqli_query($conn, $sql);

$sql = "SELECT * FROM sub_caste";
$sub_result = mysqli_query($conn, $sql);

$sql = "SELECT * FROM status";
$status_result = mysqli_query($conn, $sql);

$sql = "SELECT * FROM source";
$source_result = mysqli_query($conn, $sql);

$sql = "SELECT * FROM res_status";
$res_result = mysqli_query($conn, $sql);

$msg = '';

include("include/settings.php");
include("checksession.php");
 $lead_date = date('Y-m-d', strtotime($_POST['txtDate']));

$memberdetailmaster = $mysqli->prepare("select * from rishta_leadmaster where lead_id=?");
$memberdetailmaster->bind_param("i", $_GET['leadid']);
$memberdetailmaster->execute();
$memberdetailresult = $memberdetailmaster->get_result();




if (mysqli_num_rows($memberdetailresult) > 0) {
    $lead_id = $_GET['leadid'];
$selectedDisposition = trim($memberrow->disposition ?? '');
$selectedSource      = trim($memberrow->source ?? '');

$leadStatusValue = trim($memberrow->disposition ?? '');
$leadSourceValue = trim($memberrow->source ?? '');
 //    "<pre>";
   //   print_r($memberdetailresult);
//    "</pre>";
//die();
} else {
 //   header("location:index.php");
}

if (isset($_POST['btnSaveMember'])) {
    if (trim($_POST["txtDate"]) != null) {
        $leadtype = 'rishta_lead';

        $lead_date = date('Y-m-d', strtotime($_POST['txtDate']));

    //    $call_time_scheduling = NULL;
        if (trim($_POST["call_time_scheduling"]) != null) {
            $call_time_scheduling = date('H:i:s', strtotime($_POST['call_time_scheduling']));
        }
        else{
           $call_time_scheduling = NULL;  
        }

        $pass = 1;
        if (isset($_POST['ddlLeadAllocated']) && !empty($_POST['ddlLeadAllocated'])) {

            $check_query = "";
            $check_query .= "SELECT `lead_allocated_to` FROM rishta_leadmaster WHERE lead_allocated_to='" . $_POST['ddlLeadAllocated'] . "' AND lead_id != '" . $lead_id . "'  ";
            $checkExists = $mysqli->prepare($check_query);
            $checkExists->execute();
            $checkExists = $checkExists->get_result();
            if (mysqli_num_rows($checkExists) >= 1000) {

                $pass = 0;
                $msg = "Please Select Other Sales execute to allocate lead.";
            }
        }

        if ($pass == 1) {

           $usermaster = $mysqli->prepare("update rishta_leadmaster set lead_created=?, lead_payment=?, source=?, lead_type=?, profile_name=?, contact_name=?, relation=?, profile_contact_no=?, contact_no=?, member_status=?, profile_email=?, email_id=?, city=?, state=?, country=?, disposition=?, currency=?, amount=?, gender=?, marital_status=?, age=?, height=?, height_inches=?, education=?, employment=?, religion=?, more_info=?, caste=?, sub_caste=?, residency_status=?, lead_remarks=?, name1=?, url1=?, name2=?, url2=?, name3=?, url3=?, name4=?, url4=?, name5=?, url5=?, video_calling=?, video_link=?, call_scheduling=?, lead_reason=?, lead_allocated_to=?, lead_added_by=?,contact_name_two=?,contact_email_two=?,contact_number_two=?,smartmatch_profile_link=? where lead_id=?");
         $usermaster->bind_param(

"sssssssssssssssssssssssssssssssssssssssssssssssssssi",

$lead_date,
$_POST['txtdop'],
$_POST['txtLeadSource'],
$leadtype,

$_POST['txtcname2'], // profile_name
$_POST['txtcname'],  // contact_name

$_POST['txtrelation'],

$_POST['txtcontact2'], // profile_contact_no
$_POST['txtcontact'],

$_POST['txtmstatus'],

$_POST['txtemailid2'], // profile_email
$_POST['txtemailid'],

$_POST['txtcity'],
$_POST['txtstate'],
$_POST['txtcountry'],

$_POST['ddlLeadStatus'],

$_POST['txtcurrency'],
$_POST['txtamanual'],
$_POST['txtgender'],
$_POST['txtmarital'],
$_POST['txtage'],
$_POST['txtheight'],
$_POST['txtheightinch'],
$_POST['txtedu'],
$_POST['txtemp'],
$_POST['txtreligion'],
$_POST['txtminfo'],
$_POST['txtcaste'],
$_POST['txtsubcaste'],
$_POST['txtrstatus'],
$_POST['txtRemarks'],

$_POST['txtname1'],
$_POST['txturl1'],
$_POST['txtname2'],
$_POST['txturl2'],
$_POST['txtname3'],
$_POST['txturl3'],
$_POST['txtname4'],
$_POST['txturl4'],
$_POST['txtname5'],
$_POST['txturl5'],

$_POST['txtvideocall'],
$_POST['txtvideolink'],
$_POST['txtcall'],
$_POST['txtreason'],
$_POST['ddlLeadAllocated'],

$_SESSION['userId'],

$_POST['txtcname2'],
$_POST['txtemailid2'],
$_POST['txtcontact2'],
$_POST['txtsmartmatch'],

$lead_id

);
$usermaster->execute();
if ($usermaster->error) {
    die($usermaster->error);
}

if ($usermaster->affected_rows >= 0) {

    $memberdetailmaster = $mysqli->prepare("
        SELECT * 
        FROM rishta_leadmaster 
        WHERE lead_id = ?
    ");

    $memberdetailmaster->bind_param("i", $lead_id);
    $memberdetailmaster->execute();

    $memberdetailresult = $memberdetailmaster->get_result();

    $memberrow = mysqli_fetch_object($memberdetailresult);
}

$usermaster->close();

header("Location: edit-leads.php?leadid=" . $lead_id);
exit;

            /*$update_query = "UPDATE rishta_leadmaster SET call_time_scheduling = '" . $call_time_scheduling . "' WHERE lead_id = " . $lead_id . "  ";
            $resultData = $mysqli->prepare($update_query);
            $resultData->execute();
            $resultData->close();*/

           // $call_scheduling = NULL;
            if (trim($_POST["txtcall"]) != null) {
                $call_scheduling = date('Y-m-d', strtotime(trim($_POST['txtcall'])));
            }
            else{
                $call_scheduling = NULL; 
            }

         //   $call_time_scheduling = NULL;
            if (trim($_POST["call_time_scheduling"]) != null) {
                $call_time_scheduling = date('H:i:s', strtotime(trim($_POST['call_time_scheduling'])));
            }
             else{
                $call_time_scheduling = NULL;
            }

            $disposition = $_POST['ddlLeadStatus'];
            if (in_array($disposition, array('Follow up', 'New Call','No match shared yet','Match Shared','Close to Conversion','Fully Paid','Lead Rejected','Refund','Fresh Lead','Renewal Lead','Ptential CRM Lead','Interested','Old Leads','Expired (Not to be converted)','Inactive','Ringing','Expired','Active','Wrong Number','On Hold','Confirmed Rishta done','Old Leads','Not Interested'))) {

                if (!empty($call_scheduling) && !empty($call_time_scheduling)) {

                    $check_query = "";
                    $check_query .= "SELECT * FROM cbi_call_schedule WHERE lead_id='" . $lead_id . "' AND disposition='" . $disposition . "' AND call_scheduling='" . $call_scheduling . "' AND call_time_scheduling='" . $call_time_scheduling . "' ";
                    $checkExists = $mysqli->prepare($check_query);$sql = "SELECT * FROM source";
$source_result = mysqli_query($conn, $sql);
                    $checkExists->execute();
                    $checkExists = $checkExists->get_result();
                    if (mysqli_num_rows($checkExists) == 0) {

                        $insert_query = "";
                        $insert_query .= "INSERT INTO cbi_call_schedule SET ";
                        $insert_query .= " call_added_by = '" . $_SESSION['userId'] . "', ";
                        $insert_query .= " lead_id = '" . $lead_id . "', ";
                        $insert_query .= " disposition = '" . $disposition . "', ";
                        $insert_query .= " call_scheduling = '" . $call_scheduling . "', ";
                        $insert_query .= " call_time_scheduling = '" . $call_time_scheduling . "', ";
                        $insert_query .= " created_on = '" . date('Y-m-d H:i:s') . "' ";

                        $insertObj = $mysqli->prepare($insert_query);
                        $insertObj->execute();
                        $insertObj->close();
                    }
                }
                
                
                                if (!empty($disposition) && !empty($disposition)) {

                    $check_query = "";
                    $check_query .= "SELECT * FROM timeline WHERE lead_id='" . $lead_id . "' AND disposition='" . $disposition . "' ";
                    $checkExists = $mysqli->prepare($check_query);
                    $checkExists->execute();
                    $checkExists = $checkExists->get_result();
                    if (mysqli_num_rows($checkExists) == 0) {

                        $insert_query = "";
                        $insert_query .= "INSERT INTO timeline SET ";
                        $insert_query .= " call_added_by = '" . $_SESSION['userId'] . "', ";
                        $insert_query .= " lead_id = '" . $lead_id . "', ";
                        $insert_query .= " disposition = '" . $disposition . "', ";
                        $insert_query .= " created_on = '" . date('Y-m-d H:i:s') . "' ";

                        $insertObj = $mysqli->prepare($insert_query);
                        $insertObj->execute();
                        $insertObj->close();
                    }
                }
            }

            $msg = "Lead has been updated successfully.";
           header("Location: edit-leads.php?leadid=" . $lead_id);
exit;
        }
    } else {
        $msg = "Please enter all the fields correctly.";
    }
}

$usermaster = $mysqli->prepare("select * from cdi_usermaster where user_type='sales_exec' order by user_creationdate desc");
$usermaster->execute();
$userresult = $usermaster->get_result();


$followupmaster = $mysqli->prepare("select cdi_followups.*, cdi_usermaster.user_full_name,cdi_usermaster.user_email_id from cdi_followups inner join cdi_usermaster on cdi_followups.sales_executive_id=cdi_usermaster.user_id where lead_id=? order by followup_created_on desc");
$followupmaster->bind_param('i', $lead_id);
$followupmaster->execute();
$followresult = $followupmaster->get_result();

$followupmaster = $mysqli->prepare("select cdi_followups.*, cdi_usermaster.user_full_name,cdi_usermaster.user_email_id from cdi_followups inner join cdi_usermaster on cdi_followups.sales_executive_id=cdi_usermaster.user_id where lead_id=? order by followup_created_on desc");
$followupmaster->bind_param('i', $lead_id);
$followupmaster->execute();
$followresults = $followupmaster->get_result();



$followupmaster = $mysqli->prepare("select * from timeline where lead_id=$lead_id order by lead_id desc");
$followupmaster->bind_param('i', $lead_id);
$followupmaster->execute();
$followresults = $followupmaster->get_result();


$followupmasters = $mysqli->prepare("select * from cbi_call_schedule where lead_id=$lead_id order by lead_id desc");
$followupmasters->bind_param('i', $lead_id);
$followupmasters->execute();
$followresultss = $followupmasters->get_result();


if (!isset($condition)) {
    $condition = "";
}

/*$select_follow_query = "select *,(select count(*) from cdi_followups where lead_id = rishta_leadmaster.lead_id) as followcount  from rishta_leadmaster where lead_type='rishta_lead' " . $condition . " order by lead_created desc limit 10";*/
$select_follow_query = "select *,(select count(*) from cdi_followups where lead_id = rishta_leadmaster.lead_id) as followcount  from rishta_leadmaster where lead_type='rishta_lead' AND lead_id='" . $lead_id . "' order by lead_created desc limit 10";
$usermaster = $mysqli->prepare($select_follow_query);
/*$usermaster->bind_param('i', $lead_id);*/
$usermaster->execute();
$userresults = $usermaster->get_result();


$select_query = "";
$select_query .= " select cbi_call_schedule.*, cdi_usermaster.user_full_name,cdi_usermaster.user_email_id from cbi_call_schedule inner join cdi_usermaster on cbi_call_schedule.call_added_by=cdi_usermaster.user_id ";
$select_query .= " where lead_id=? order by call_scheduling desc limit 10";
$resultCallSchedule = $mysqli->prepare($select_query);
$resultCallSchedule->bind_param('i', $lead_id);
$resultCallSchedule->execute();
$resultCallSchedule = $resultCallSchedule->get_result();


if(isset($_POST['btnSaveFollowUp']))
{
	if(trim($_POST["txtFollowup"])!=null && trim($_POST["txtFollowupTakenOn"])!=null)
	{		
		$followupmaster=$mysqli->prepare("INSERT INTO cdi_followups(lead_id,sales_executive_id,followup_description,followup_created_on,entry_created_on) VALUES (?,?,?,?,?)");
		$followupmaster->bind_param("iisss",$lead_id,$_SESSION['userId'],$_POST['txtFollowup'],$_POST['txtFollowupTakenOn'],$thisdate);
		$followupmaster->execute();
		$followupmaster->close();
		
		$msg="Follow Up is added successfully.";
	//	header( "refresh:2;url=followlead.php?leadid=".$lead_id."&is_p=".$is_p);

	}
	else
	{
		$msg="Please enter all the fields correctly.";
	}
}




// Email send code



$memberdetailmaster = $mysqli->prepare("select * from rishta_leadmaster where lead_id=?");
$memberdetailmaster->bind_param("i", $_GET['leadid']);
$memberdetailmaster->execute();
$memberdetailresult = $memberdetailmaster->get_result();

$memberrow = mysqli_fetch_object($memberdetailresult);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

if(isset($_POST['btnSaveMembers'])) {

    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';

    $mail = new PHPMailer(true);

    try {

        // ---- SMTP CONFIG (cPanel) ----
     $mail->isSMTP();
$mail->Host       = 'localhost';
$mail->SMTPAuth   = true;
$mail->Username   = 'info@rishtasite.in';
$mail->Password   = 'Sailor@12345';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port       = 465;
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            )
        );

        // ---- SENDER ----
        $mail->setFrom('info@rishtasite.in', 'Rishta Depot');

        // ---- RECIPIENT from DB ----
        $leadid  = $_GET['leadid'];
        $getLead = $mysqli->prepare("SELECT * FROM rishta_leadmaster WHERE lead_id=?");
        $getLead->bind_param("i", $leadid);
        $getLead->execute();
        $result  = $getLead->get_result();
        $row     = $result->fetch_assoc();

        $txtemailid = trim($row['email_id']);
        $txtcname   = trim($row['contact_name']);

        if (empty($txtemailid) || !filter_var($txtemailid, FILTER_VALIDATE_EMAIL)) {
            $msg = "Invalid or empty recipient email address.";
        } else {

           $mail->addAddress($txtemailid, $txtcname);               
$mail->addBCC('aaadriversacademyca@gmail.com', 'Admin Notification'); 

            // ---- EMAIL CONTENT ----
            $mail->isHTML(true);
            $mail->Subject = $_POST['txtSubject'];
            $mail->Body    = '<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background-color:#fff7df;font-family:Arial,sans-serif;">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td align="center" style="padding:20px 0;">
<table border="0" cellpadding="0" cellspacing="0" width="600" style="background:#ffffff;border-radius:8px;">
<tr><td align="center" style="padding:30px 20px 10px;">
  <img src="https://rishtasite.com/assets/images/logo-black.png" style="width:180px;height:auto;" alt="Rishta Depot">
</td></tr>
<tr><td align="center" style="padding:10px 20px;">
  <h1 style="font-size:22px;color:#333;">Message from Rishta Depot</h1>
</td></tr>
<tr><td align="center" style="padding:10px 30px;">
  <p style="font-size:15px;color:#555;line-height:1.6;">' . nl2br(htmlspecialchars($_POST['txtMessage'])) . '</p>
</td></tr>
<tr><td align="center" style="padding:20px;">
  <a href="https://rishtasite.com/" style="background-color:#f36f21;color:#fff;padding:10px 24px;border-radius:4px;text-decoration:none;font-size:14px;">Visit our website</a>
</td></tr>
<tr><td style="padding:20px 30px;border-top:2px solid #f36f21;margin-top:20px;">
  <p style="font-size:13px;color:#888;text-align:center;margin:0;">
    RishtaDepot is a matrimonial service powered by world-class matchmakers.<br>
    Address: 21 King Street West, 5th Floor, Hamilton, Ontario, L8P 4W7, Canada<br>
    Phone: +91 9054811166
  </p>
  <p style="text-align:center;margin:10px 0 0;">
    <a href="https://www.facebook.com/rishtadepotcom" style="margin:0 5px;">Facebook</a>
    <a href="https://www.instagram.com/rishtadepot_official/" style="margin:0 5px;">Instagram</a>
    <a href="https://www.youtube.com/channel/UC7vBgqrX1JTECSLK1amee7Q" style="margin:0 5px;">YouTube</a>
  </p>
  <p style="font-size:11px;color:#aaa;text-align:center;margin:8px 0 0;">&copy; 2024 Rishta Depot. All Rights Reserved.</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>';

            // ---- SEND ----
            $mail->send();
            $msg = "Email has been sent successfully!";
        }

    } catch (Exception $e) {
        $msg = "Email could not be sent. Error: " . $mail->ErrorInfo;
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="description" content="">
	<meta name="author" content="">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/countrystatecity.js"></script>

	<title>Update Rishta Leads - Rishta Depot </title>

	<style>
		.required{
	    color:red;
	}
		body {
			font-family: Arial, Helvetica, sans-serif;
		}

		* {
			box-sizing: border-box;
		}

		/* Button used to open the contact form - fixed at the bottom of the page */
		.open-button {
			background-color: #555;
			color: white;
			padding: 16px 20px;
			border: none;
			cursor: pointer;
			opacity: 0.8;
			position: fixed;
			bottom: 23px;
			right: -28px;
			width: 280px;
		}

		/* The popup form - hidden by default */
		.form-popup {
			display: none;
			position: fixed;
			bottom: 200px;
			right: 270px;
			border: 3px solid #f1f1f1;
			z-index: 9;
			background-color: white;
			border-radius: 8px;
		}

		/* Add styles to the form container */
		.form-container {
			max-width: 3000px;
			padding: 10px;
			background-color: white;
		}

		/* Full-width input fields */
		.form-container input[type=text],
		.form-container input[type=password] {
			width: 100%;
			padding: 15px;
			margin: 5px 0 22px 0;
			border: none;
			background: #f1f1f1;
		}

		/* When the inputs get focus, do something */
		.form-container input[type=text]:focus,
		.form-container input[type=password]:focus {
			background-color: #ddd;
			outline: none;
		}

		/* Set a style for the submit/login button */
		.form-container .btn {
			background-color: #04AA6D;
			color: white;
			padding: 16px 20px;
			border: none;
			cursor: pointer;
			width: 100%;
			margin-bottom: 10px;
			opacity: 0.8;
		}

		/* Add a red background color to the cancel button */
		.form-container .cancel {
			background-color: red;
		}

		/* Add some hover effects to buttons */
		.form-container .btn:hover,
		.open-button:hover {
			opacity: 1;
		}
	</style>
	<?php include('./include/meta.php'); ?>

</head>

<?php include('./include/header.php'); ?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
	<div class="container-full">
		<!-- Content Header (Page header) -->
		<div class="content-header">
			<div class="d-flex align-items-center">
				<div class="me-auto">
					<h4 class="page-title">Forms</h4>
					<div class="d-inline-block align-items-center">
						<nav>
							<ol class="breadcrumb">
								<li class="breadcrumb-item"><a href="#"><i class="mdi mdi-home-outline"></i></a></li>
								<li class="breadcrumb-item" aria-current="page">Update Rishta Lead</li>
								<li class="breadcrumb-item active" aria-current="page">Forms</li>
							</ol>
						</nav>
					</div>



				</div>
			</div>

			<!-- Main content -->
			<section class="content">
				<div class="row">
					<div class="col-12">
						<div class="box">
							<div class="box-header with-border">
								<h4 class="box-title">Update Rishta Leads</h4>
								<button class="btn btn-secondary btn-sm" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
									Timeline
								</button>
							
								<button type="button" id="modalButton" class="btn btn-info" data-toggle="modal" data-target="#myModal">Send Mail</button> 
								
								<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
									<div class=" col-12">

										<div class="box-header with-border">
											<h3 class="box-title">Timeline Status</h3>
										</div>
										<div class="row">
											<div class="box-body">

												<ul class="events-list">
												    
												      <?php
                            if (mysqli_num_rows($followresults) > 0) {
                                ?>
                                  <?php
                                    $i = 0;
                                    while ($fuserrows = mysqli_fetch_object($followresults)) {
                                        $i++;
                                        ?>
													<li>
														<time datetime="<?php echo $fuserrows->created_on ?>"><?php echo $fuserrows->created_on ?></time>
														<span><strong><?php echo $fuserrows->disposition ?></strong></span>
													</li>
													   <?php
                                    }
                                    ?>
                                    
                                 <?php
                                        }
                                    ?>
												

													<!--li>
														<time datetime=""></time>
														<span><strong>Current Stage</strong> <?php //echo $memberrow->disposition ?></span>
													</li>

													<li>
														<time datetime=""></time>
														
													
														<span><strong>Created</strong> <?php //echo $memberrow->lead_created ?> </span>
													</li-->
												</ul>
											</div>	
										</div>
									</div>
								</div>
							
									
										<p>Assigned Advisor Name:-  	<?php
								
								  $lead_allocated=  $memberrow->lead_allocated_to ;
								  
								    $user = $mysqli->prepare("select * from cdi_usermaster where user_id=$lead_allocated");
                                    $user->execute();
                                    $useres = $user->get_result();
                                     $e_name= mysqli_fetch_object($useres);
                                     
                                    // echo $e_name->user_full_name;
								?>
								
							<strong><p><?php echo $e_name->user_full_name; ?></p></strong>	
							</div>
							<!-- /.box-header -->
						
							        <form action="#" method="post" class="form" enctype="multipart/form-data">
								<div class="box-body">
								    <?php
                    if (trim($msg) != null) {
                        ?>
                        <div class='row'>
                            <div class='col-md-12'>
                                <div class="alert alert-success errormessage" id="errormessage">
                                    <strong><?php echo $msg ?></strong>
                                </div>
                            </div>
                        </div>
                        <?php
                    }
                    ?>
                    	<center> <strong><h3 class="box-title">Lead Details</h3></strong>  </center>	  
									<div class="row">
										<div class="col-md-6">
                									<div class="form-group">
    <label class="form-label">Lead Status</label>
    <span class="required">*</span>

    <select id="ddlLeadStatus" name="ddlLeadStatus" class="form-select">
        <option value="">Lead Status</option>

        <?php
        $statusQuery = $mysqli->query("SELECT * FROM status ORDER BY name ASC");

        while ($statusRow = $statusQuery->fetch_assoc()) {

            $statusName = trim($statusRow['name']);
            $selected   = '';

            if (trim($memberrow->disposition ?? '') === $statusName) {
                $selected = 'selected';
            }
        ?>

            <option value="<?php echo htmlspecialchars($statusName); ?>" <?php echo $selected; ?>>
                <?php echo htmlspecialchars($statusName); ?>
            </option>

        <?php } ?>
    </select>
</div>

											
										</div>
										<div class="col-md-6">
                                            <div class="form-group">
    <label class="form-label">Lead Source</label>
    <span class="required">*</span>

    <select id="txtLeadSource" name="txtLeadSource" class="form-select">
        <option value="">Lead Source</option>

        <?php
        $sourceQuery = $mysqli->query("SELECT * FROM source ORDER BY name ASC");

        while ($sourceRow = $sourceQuery->fetch_assoc()) {

            $sourceName = trim($sourceRow['name']);
            $selected   = '';

            if (trim($memberrow->source ?? '') === $sourceName) {
                $selected = 'selected';
            }
        ?>

            <option value="<?php echo htmlspecialchars($sourceName); ?>" <?php echo $selected; ?>>
                <?php echo htmlspecialchars($sourceName); ?>
            </option>

        <?php } ?>
    </select>
</div>
										</div>
									</div>
						
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Member Status</label>
										  <select id="txtmstatus" name="txtmstatus" class="form-select">
                                <option value="">Member Status</option>
                                <option <?php echo $memberrow->member_status == '#2' ? 'selected' : '' ?> value="#2">#2</option>
                                <option <?php echo $memberrow->member_status == '#3' ? 'selected' : '' ?> value="#3">#3</option>
                                <option <?php echo $memberrow->member_status == '#4' ? 'selected' : '' ?> value="#4">#4</option>
                            </select>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Country</label>

<select name="txtcountry" class="countries form-select" id="countryId">
    <option value="">Select Country</option>
</select>



											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">State</label>
											<select name="txtstate" class="states form-select" id="stateId">
    <option value="<?php echo htmlspecialchars($memberrow->state); ?>">
        <?php echo htmlspecialchars($memberrow->state); ?>
    </option>
</select>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">City</label>
											<select name="txtcity" class="cities form-select" id="cityId">
    <option value="<?php echo htmlspecialchars($memberrow->city); ?>">
        <?php echo htmlspecialchars($memberrow->city); ?>
    </option>
</select>
											</div>
										</div>
									</div>
												<div class="row">
	
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Payment Date</label>
												 <input type="text" maxlength="200" id="txtdop" placeholder="payment date" name="txtdop" class="form-control" value='<?php echo $memberrow->lead_payment ?>'/>
											</div>
										</div>
									</div>
								 <hr style="height:10px;">
                                <center><strong><h3 class="box-title">1st Contact Information</h3></strong></center>

                                <!-- Contact Name + Phone -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Contact 1 Name</label><span class="required">*</span>
                                            <input type="text"
maxlength="50"
id="txtcname"
name="txtcname"
class="form-control"
placeholder="Name"
value="<?php echo htmlspecialchars($memberrow->contact_name ?? ''); ?>"/>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Contact 1 Phone Number</label><span class="required">*</span>
                                            <input type="text" maxlength="15" id="txtcontact" name="txtcontact" class="form-control" 
       placeholder="Phone Number" value="<?php echo htmlspecialchars($memberrow->contact_no ?? ''); ?>"/>

                                        </div>
                                    </div>
                                </div>

                                <!-- Email + Relation -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Contact 1 Email-ID</label><span class="required">*</span>
<input type="text" id="txtemailid" autocomplete="off" name="txtemailid" class="form-control" 
       placeholder="Contact Email-ID" value="<?php echo htmlspecialchars($memberrow->email_id ?? ''); ?>"/>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Relation</label>
                                            <select class="form-select" name="txtrelation" id="txtrelation">
                                                <option value="">Relation</option>
                                                <?php
                                                $relations = ['Match','Father','Mother','Brother','Sister','Brother-in-law',
                                                    'Bhabi Ji','Chacha Ji','Chachi Ji','Mama Ji','Mami Ji','Bhua Ji',
                                                    'Fufar Ji','Masi Ji','Masar Ji','Dada Ji','Dadi Ji','Dewar',
                                                    'Dewrani','Nana Ji','Nani Ji','Taya Ji','Tayi Ji','Friend','Self'];
                                                foreach ($relations as $rel):
                                                ?>
                                                    <option value="<?php echo $rel; ?>"
<?php if($memberrow->relation == $rel){ echo 'selected'; } ?>>
<?php echo $rel; ?>
</option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Gender + Marital Status (ADDED - were commented out but needed for filter) -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Gender</label>
                                           <select id="txtgender" name="txtgender" class="form-select">

    <option value="">Gender</option>

    <option value="Male"
    <?php if($memberrow->gender=='Male'){ echo 'selected'; } ?>>
    Male
    </option>

    <option value="Female"
    <?php if($memberrow->gender=='Female'){ echo 'selected'; } ?>>
    Female
    </option>

</select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Marital Status</label>
                                            <select id="txtmarital" name="txtmarital" class="form-select">

<option value="">Marital Status</option>

<option value="Never Married"
<?php if($memberrow->marital_status=='Never Married'){ echo 'selected'; } ?>>
Never Married
</option>

<option value="Annulled"
<?php if($memberrow->marital_status=='Annulled'){ echo 'selected'; } ?>>
Annulled
</option>

<option value="Divorced No Kids"
<?php if($memberrow->marital_status=='Divorced No Kids'){ echo 'selected'; } ?>>
Divorced No Kids
</option>

<option value="Widow"
<?php if($memberrow->marital_status=='Widow'){ echo 'selected'; } ?>>
Widow
</option>

</select>
                                        </div>
                                    </div>
                                </div>

                                <!-- Age + Residency Status (ADDED) -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="form-label">Age</label>
                                            <select class="form-select" name="txtage" id="txtage">

<option value="<?php echo $memberrow->age; ?>">
<?php echo $memberrow->age; ?>
</option>

<?php for ($i = 18; $i <= 75; $i++): ?>

<option value="<?php echo $i; ?>">
<?php echo $i; ?>
</option>

<?php endfor; ?>

</select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
    <label class="form-label">Residency Status</label>

    <select id="txtrstatus" name="txtrstatus" class="form-select">
        <option value="">Residency Status</option>

        <?php
        // Fresh query instead of reusing exhausted result set
        $resQuery = $mysqli->query("SELECT * FROM res_status ORDER BY name ASC");

        while ($row = $resQuery->fetch_assoc()) {

            $selected = '';

            if (trim($memberrow->residency_status ?? '') == trim($row['name'])) {
                $selected = 'selected';
            }
        ?>

            <option value="<?php echo htmlspecialchars($row['name']); ?>" <?php echo $selected; ?>>
                <?php echo htmlspecialchars($row['name']); ?>
            </option>

        <?php } ?>
    </select>
</div>
                                    </div>
                                </div>
                                
                                <div class="row">

    <!-- Amount -->
    <div class="col-md-6">
        <div class="form-group">
            <label class="form-label">Amount</label>

            <input type="number"
                   id="txtamanual"
                   name="txtamanual"
                   class="form-control"
                   placeholder="Enter Amount"
                   value="<?php echo htmlspecialchars($memberrow->amount ?? ''); ?>" />
        </div>
    </div>

    <!-- Currency -->
    <div class="col-md-6">
        <div class="form-group">
            <label class="form-label">Currency</label>

            <select id="txtcurrency"
                    name="txtcurrency"
                    class="form-select">

                <option value="">Currency</option>

                <option value="INR"
                <?php if(($memberrow->currency ?? '')=='INR'){ echo 'selected'; } ?>>
                INR
                </option>

                <option value="US Dollar"
                <?php if(($memberrow->currency ?? '')=='US Dollar'){ echo 'selected'; } ?>>
                US Dollar
                </option>

                <option value="Canadian Dollar"
                <?php if(($memberrow->currency ?? '')=='Canadian Dollar'){ echo 'selected'; } ?>>
                Canadian Dollar
                </option>

                <option value="Pound"
                <?php if(($memberrow->currency ?? '')=='Pound'){ echo 'selected'; } ?>>
                Pound
                </option>

                <option value="USD"
                <?php if(($memberrow->currency ?? '')=='USD'){ echo 'selected'; } ?>>
                USD
                </option>

                <option value="CAD"
                <?php if(($memberrow->currency ?? '')=='CAD'){ echo 'selected'; } ?>>
                CAD
                </option>

                <option value="GBP"
                <?php if(($memberrow->currency ?? '')=='GBP'){ echo 'selected'; } ?>>
                GBP
                </option>

                <option value="AUD"
                <?php if(($memberrow->currency ?? '')=='AUD'){ echo 'selected'; } ?>>
                AUD
                </option>

            </select>
        </div>
    </div>

</div>
									
																	<hr style="height:10px;">
									<center> <strong><h3 class="box-title">Profile Information </h3></strong>  </center>
								
								<div class="row">

    <div class="col-md-6">
        <div class="form-group">
            <label class="form-label">Profile Name</label>

            <input type="text"
                   maxlength="50"
                   id="txtcname2"
                   name="txtcname2"
                   class="form-control"
                   placeholder="Profile Name"
                   value="<?php echo $memberrow->contact_name_two ?>" />
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label class="form-label">SmartMatch Profile Link</label>

            <input type="text"
                   maxlength="255"
                   id="txtsmartmatch"
                   name="txtsmartmatch"
                   class="form-control"
                   placeholder="SmartMatch Profile Link"
                   value="<?php echo $memberrow->smartmatch_profile_link ?>" />
        </div>
    </div>

</div>

<div class="row">

    <div class="col-md-6">
        <div class="form-group">
            <label class="form-label">Profile Phone No.</label>

            <input type="text"
                   maxlength="15"
                   id="txtcontact2"
                   name="txtcontact2"
                   class="form-control"
                   placeholder="Profile Phone No."
                   value="<?php echo $memberrow->contact_number_two ?>" />
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label class="form-label">Profile Email-ID</label>

            <input type="text"
                   id="txtemailid2"
                   autocomplete="off"
                   name="txtemailid2"
                   class="form-control"
                   placeholder="Profile Email-ID"
                   value="<?php echo $memberrow->contact_email_two ?>" />
        </div>
    </div>

</div>
								
							
									
							 
									
									<!--	<hr style="height:10px;">
										<center> <strong><h3 class="box-title">Profile Information </h3></strong>  </center>
									<div class="row">
													<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Profile Name</label>
											   <input type="text" maxlength="200" id="txtpname" name="txtpname" class="form-control" value="<?php echo $memberrow->profile_name ?>"/>
											</div>
										</div>
								
									    	<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Profile Phone No.</label>
											      <input type="text" maxlength="15" id="txtpcontact" name="txtpcontact" class="form-control" value="<?php echo $memberrow->profile_contact_no ?>"/>
											</div>
										</div>
									</div>
										<div class="row">
										    	<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Profile Email-ID</label>
											 <input type="text" id="txtemail" autocomplete='off' name="txtemail" class="form-control" value="<?php echo $memberrow->profile_email ?>"/>
											</div>
										</div>
														<div class="col-md-6">
							<div class="form-group">
    <label class="form-label">Residency Status</label>
    <select id="txtrstatus" name="txtrstatus" class="form-select">
        <option value="">Residency Status</option>
        <?php 
        if (mysqli_num_rows($res_result) > 0) {
            while($row = mysqli_fetch_assoc($res_result)) { 
                $selected = ($memberrow->residency_status == $row['name']) ? 'selected' : '';
                ?> 
                <option value="<?php echo $row['name']; ?>" <?php echo $selected; ?>>
                    <?php echo $row['name']; ?> 
                </option> 
            <?php }
        } ?>
    </select>
</div>
										</div>
										    </div>
									
									
								
									<hr style="height:10px;">
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Age</label>
											<select class="form-select" name="txtage" id="txtage" value="<?php echo $memberrow->age ?>">
                                <option value="<?php echo $memberrow->age ?>"><?php echo $memberrow->age ?></option>
                                <?php for ($i = 18; $i <= 75; $i++) { ?>
                                    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                <?php } ?>
                            </select>
											</div>
										</div>
										<div class="col-md-3">
											<div class="form-group">
												<label class="form-label">Height</label>
											 <select id="txtheight" name="txtheight" class="form-select">
                                <option value=""></option>
                                <option <?php echo $memberrow->height == '4' ? 'selected' : '' ?> value="4">4</option>
                                <option <?php echo $memberrow->height == '5' ? 'selected' : '' ?> value="5">5</option>
                                <option <?php echo $memberrow->height == '6' ? 'selected' : '' ?> value="6">6</option>
                                <option <?php echo $memberrow->height == '7' ? 'selected' : '' ?> value="7">7</option>
                            </select>
											</div>
										</div>
										<div class="col-md-3">
											<div class="form-group">
												<label class="form-label">Inch</label>
											    <select id="txtheightinch" name="txtheightinch" class="form-select">
                                <option value=""></option>
                                <option <?php echo $memberrow->height_inches == '0' ? 'selected' : '' ?> value="0">0</option>
                                <option <?php echo $memberrow->height_inches == '1' ? 'selected' : '' ?> value="1">1</option>
                                <option <?php echo $memberrow->height_inches == '2' ? 'selected' : '' ?> value="2">2</option>
                                <option <?php echo $memberrow->height_inches == '3' ? 'selected' : '' ?> value="3">3</option>
                                <option <?php echo $memberrow->height_inches == '4' ? 'selected' : '' ?> value="4">4</option>
                                <option <?php echo $memberrow->height_inches == '5' ? 'selected' : '' ?> value="5">5</option>
                                <option <?php echo $memberrow->height_inches == '6' ? 'selected' : '' ?> value="6">6</option>
                                <option <?php echo $memberrow->height_inches == '7' ? 'selected' : '' ?> value="7">7</option>
                                <option <?php echo $memberrow->height_inches == '8' ? 'selected' : '' ?> value="8">8</option>
                                <option <?php echo $memberrow->height_inches == '9' ? 'selected' : '' ?> value="9">9</option>
                                <option <?php echo $memberrow->height_inches == '10' ? 'selected' : '' ?> value="10">10</option>
                                <option <?php echo $memberrow->height_inches == '11' ? 'selected' : '' ?> value="11">11</option>
                            </select>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Education</label>
											<input type="text" maxlength="50" id="txtedu" name="txtedu" class="form-control" value="<?php echo $memberrow->education ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Employment</label>
											<input type="text" maxlength="50" id="txtemp" name="txtemp" class="form-control" value="<?php echo $memberrow->employment ?>"/>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
                        			<div class="form-group">
                            <label class="form-label">Religion</label>
                            <select id="txtreligion" name="txtreligion" class="form-select">
                                <option value="">Religion</option>
                                <?php 
                                if (mysqli_num_rows($sub_result) > 0) {
                                    while($row = mysqli_fetch_assoc($sub_result)) { 
                                        $selected = ($memberrow->religion == $row['name']) ? 'selected' : '';
                                        ?> 
                                        <option value="<?php echo $row['name']; ?>" <?php echo $selected; ?>>
                                            <?php echo $row['name']; ?> 
                                        </option> 
                                    <?php }
                                } ?>
                            </select>
                        </div>
										</div>
										<div class="col-md-6">
<div class="form-group">
    <label class="form-label">Caste</label>
    <select id="txtcaste" name="txtcaste" class="form-select">
        <option value="">Caste</option>
        <?php 
        if (mysqli_num_rows($caste_result) > 0) {
            while($row = mysqli_fetch_assoc($caste_result)) { 
                $selected = ($memberrow->caste == $row['name']) ? 'selected' : '';
                ?> 
                <option value="<?php echo $row['name']; ?>" <?php echo $selected; ?>>
                    <?php echo $row['name']; ?> 
                </option> 
            <?php }
        } ?>
    </select>
</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Sub Caste</label>
											     <input type="text" maxlength="50" id="txtsubcaste" name="txtsubcaste" class="form-control" value="<?php echo $memberrow->sub_caste ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Gender</label>
											   <select id="txtgender" name="txtgender" class="form-select">
                                <option value="">Gender</option>
                                <option <?php echo $memberrow->gender == 'Male' ? 'selected' : '' ?> value="Male">Male</option>
                                <option <?php echo $memberrow->gender == 'Female' ? 'selected' : '' ?> value="Female">Female</option>
                            </select>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Marital Status</label>
											  <select id="txtmarital" name="txtmarital" class="form-select">
                                <option value="">Marital Status</option>
                                <option <?php echo $memberrow->marital_status == 'Never Married' ? 'selected' : '' ?> value="Never Married">Never Married</option>
                                <option <?php echo $memberrow->marital_status == 'Annulled' ? 'selected' : '' ?> value="Annulled">Annulled</option>
                                <option <?php echo $memberrow->marital_status == 'Not Living Together' ? 'selected' : '' ?> value="Not Living Together">Not Living Together</option>
                                <option <?php echo $memberrow->marital_status == 'Divorce Awaited' ? 'selected' : '' ?> value="Divorce Awaited">Divorce Awaited</option>
                                <option <?php echo $memberrow->marital_status == 'Divorced No Kids' ? 'selected' : '' ?> value="Divorced No Kids">Divorced No Kids</option>
                                <option <?php echo $memberrow->marital_status == 'Divorced 1 Child' ? 'selected' : '' ?> value="Divorced 1 Child">Divorced 1 Child</option>
                                <option <?php echo $memberrow->marital_status == 'Divorced 2 Children' ? 'selected' : '' ?> value="Divorced 2 Children">Divorced 2 Children</option>
                                <option <?php echo $memberrow->marital_status == 'Divorced 3 Children' ? 'selected' : '' ?> value="Divorced 3 Children">Divorced 3 Children</option>
                                <option <?php echo $memberrow->marital_status == 'Widow' ? 'selected' : '' ?> value="Widow">Widow</option>
                            </select>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Currency</label>
										     <select id="txtcurrency" name="txtcurrency" class="form-select">
                                <option value="">Currency</option>
                                <option <?php echo $memberrow->currency == 'INR' ? 'selected' : '' ?> value="INR">INR</option>
                                <option <?php echo $memberrow->currency == 'US Dollar' ? 'selected' : '' ?> value="US Dollar">US Dollar</option>
                                <option <?php echo $memberrow->currency == 'Canadian Dollar' ? 'selected' : '' ?> value="Canadian Dollar">Canadian Dollar</option>
                                <option <?php echo $memberrow->currency == 'Pound' ? 'selected' : '' ?> value="Pound">Pound</option>
                                <option <?php echo $memberrow->currency == 'USD' ? 'selected' : '' ?> value="USD">USD</option>
                                <option <?php echo $memberrow->currency == 'CAD' ? 'selected' : '' ?> value="CAD">CAD</option>
                                <option <?php echo $memberrow->currency == 'GBP' ? 'selected' : '' ?> value="GBP">GBP</option>
                                <option <?php echo $memberrow->currency == 'AUD' ? 'selected' : '' ?> value="AUD">AUD</option>
                            </select>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Amount</label>
											 <input type="text" maxlength="50" id="txtamanual" name="txtamanual" class="form-control" value="<?php echo $memberrow->amount ?>"/>
											</div>
										</div>
									</div> -->
									<hr style="height:10px;">
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Name 1</label>
											   <input type="text" maxlength="200" id="txtname1" name="txtname1" class="form-control" value="<?php echo $memberrow->name1 ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">URL 1</label>
												   <input type="text" maxlength="250" id="txturl1" name="txturl1" class="form-control" value="<?php echo $memberrow->url1 ?>"/>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Name 2</label>
												         <input type="text" maxlength="200" id="txtname2" name="txtname2" class="form-control" value="<?php echo $memberrow->name2 ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">URL 2</label>
												 <input type="text" maxlength="250" id="txturl2" name="txturl2" class="form-control" value="<?php echo $memberrow->url2 ?>"/>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Name 3</label>
												   <input type="text" maxlength="50" id="txtname3" name="txtname3" class="form-control" value="<?php echo $memberrow->name3 ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">URL 3</label>
												<input type="text" maxlength="250" id="txturl3" name="txturl3" class="form-control" value="<?php echo $memberrow->url3 ?>"/>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Name 4</label>
												  <input type="text" maxlength="50" id="txtname4" name="txtname4" class="form-control" value="<?php echo $memberrow->name4 ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">URL 4</label>
											    <input type="text" maxlength="250" id="txturl4" name="txturl4" class="form-control" value="<?php echo $memberrow->url4 ?>"/>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Name 5</label>
											   <input type="text" maxlength="200" id="txtname5" name="txtname5" class="form-control" value="<?php echo $memberrow->name5 ?>"/>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">URL 5</label>
											         <input type="text" maxlength="250" id="txturl5" name="txturl5" class="form-control" value="<?php echo $memberrow->url5 ?>"/>
											</div>
										</div>
									</div>
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Video Calling</label>
											     <select id="txtvideocall" name="txtvideocall" class="form-select">
                                <option value="">Video Calling </option>
                                <option <?php echo $memberrow->video_calling == 'Yes' ? 'selected' : '' ?> value="Yes">Yes</option>
                                <option <?php echo $memberrow->video_calling == 'No' ? 'selected' : '' ?> value="No">No</option>
                            </select>
											</div>
										</div>
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Video Link</label>
										  <input type="text" maxlength="250" id="txtvideolink" name="txtvideolink" class="form-control" value="<?php echo $memberrow->video_link ?>"/>
											</div>
										</div>
									</div>
							                    <div class="row">
                        <div class="col-md-2">
                            <label>Reject the lead</label>
                        </div>
                        <div class="col-md-4">
                            <select id="ddlLeadAllocated" name="ddlLeadAllocated" class="form-select">

                                <option value="<?php echo $memberrow->lead_allocated_to ?>">Current User</option>
                                <option value="41">Rejected</option>
                            </select>
                               <label>Created on</label>
                            <input type="text" id="txtDates" name="txtDates" class="form-control" autocomplete='off' readonly='readonly' value="<?php echo $memberrow->lead_created_on ?>"/>
                        
                        </div>
                    </div>
							
									<h4 class="box-title text-info mb-0 mt-20"><i class="ti-user me-15"></i> Notes</h4>
									<hr style="height:2px;">
									<div class="row">
										<!-- <div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Match Preferences</label>
												               <textarea maxlength="500" style='height:100px' id="txtminfo" name="txtminfo" class="form-control"><?php echo $memberrow->more_info ?></textarea>
											</div>
										</div> -->
										<div class="col-md-12">
											<div class="form-group">
												<label class="form-label">Notes</label>
										  <textarea maxlength="500" style='height:100px' id="txtRemarks" readonly='readonly' name="txtRemarks" class="form-control"><?php echo $memberrow->lead_remarks ?></textarea>
                         
											</div>
										</div>
									</div>
									<div class="box-footer" style="border-top:0px">
										<button type="button" class="btn btn-primary" onclick="openForm()" style="margin-left: -14px;margin-top: -20px;margin-bottom: -20px;">Add Notes</button>

										<div class="form-popup" id="myForm">
											<form action="#" class="form">
												<div class="box-header with-border" style="text-align:center;">
													<h3 class="box-title">Manage Notes</h3>
												</div>
												<div class="box-body">
													<div class="row">
														<div class="col-md-6">
															<div class="form-group">
																<label class="form-label">Description</label>
																<textarea maxlength="500" style='height:100px' type="text" class="form-control" placeholder="Description" id="txtFollowup" name="txtFollowup"> </textarea>
															</div>
														</div>
														<div class="col-md-6">
															<div class="form-group">
																<label class="form-label">Note Taken On</label>
																<input type="date" placeholder="Note Taken On"  id="txtFollowupTakenOn" name="txtFollowupTakenOn"  class="form-control" value="<?php echo date('Y-m-d') ?>" " />
																
											
															</div>
														</div>
													</div>
													<div class="box-footer">
														
															<!--i class="ti-save-alt"></i>Add Follow Up </button-->
																	<button style="background-color: #7047ee;" type="submit" id="btnSaveFollowUp" name="btnSaveFollowUp" value="Add Follow Up" class="btn btn-primary" onclick="return saveusers()"/>Add</button>
																		
														<!--button type="submit" class="btn btn-primary">
															<i class="ti-save-alt"></i>View Lead Detail </button-->
														<button type="button" class="btn btn-warning me-1" onclick="closeForm()">
															<i class="ti-trash"></i> Cancel </button>
													</div>
												</div>
											</form>
										</div>
									</div>
																        <div class="col-md-12">
                            <?php
                            if (mysqli_num_rows($followresult) > 0) {
                                ?>

                                <table class="table table-responsive table-stripped table-bordered">
                                    <thead>
                                    <tr class='alert alert-warning'>
                                        <th>Sr.No</th>
                                        <th>Sales Exec.</th>
                                        <th>Sales Exec. Email</th>
                                        <th>Note</th>
                                        <th>Note Taken On</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    $i = 0;
                                    while ($fuserrow = mysqli_fetch_object($followresult)) {
                                        $i++;
                                        ?>
                                        <tr class="text-center">
                                            <td><?php echo $i; ?></td>
                                            <td class="text-left"><?php echo $fuserrow->user_full_name ?></td>
                                            <td class="text-left"><?php echo $fuserrow->user_email_id ?></td>
                                            <td class="text-left"><?php echo nl2br($fuserrow->followup_description) ?></td>
                                            <td><?php echo $fuserrow->followup_created_on ?></td>
                                        </tr>
                                        <?php
                                    }
                                    ?>
                                    </tbody>
                                </table>
                                <?php
                            } else {
                                ?>
                                <div class='row'>
                                    <div class='col-md-12'>
                                        <div class="alert alert-danger">
                                            <strong>Warning!</strong> You have no Notes for this lead.
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                            ?>
                        </div>
									<hr style="height:2px;">
									<div class="row">
										<div class="col-md-6">
											<div class="form-group">
												<!--label class="form-label">Next Date of Call</label><span class="required">*</span-->
												<label class="form-label">Next Date of Call</label>
												 <input type="date" maxlength="50" id="txtcall" name="txtcall" class="form-control" value="<?php echo $memberrow->call_scheduling ?>" />
										
											</div>
										</div>
											<div class="col-md-6">
											<div class="form-group">
												<!--label class="form-label">Next Time of Call</label><span class="required">*</span-->
												<label class="form-label">Next Time of Call</label>
												 <input type="time" id="call_time_scheduling" name="call_time_scheduling" class="form-control" value="<?php echo $memberrow->call_time_scheduling ?>" />
										
											</div>
										</div>
																			</div>
																			<div class="row">  
										<div class="col-md-6">
											<div class="form-group">
												<label class="form-label">Created On</label>
											      <input  type="text" id="txtDates" name="txtDates" class="form-control" autocomplete='off' readonly='readonly' value="<?php echo $memberrow->lead_created_on ?>"/>
											      <input value="<?php echo date('Y-m-d') ?>" type="hidden" id="txtDate" name="txtDate" class="form-control" autocomplete='off' readonly='readonly' />
											</div>
										</div>  
									</div>
									<div class="box-footer">
									
											<!--i class="ti-save-alt"></i> Save</button-->
											<button type="submit" id="btnSaveMember" style="background-color:#7047ee; color:white;"name="btnSaveMember" value="Save" class="btn btn primary" onclick="return saveuser()"/>Save </button>
										<button type="button" class="btn btn-warning me-1">
											<i class="ti-trash"></i> Cancel</button>
									</div>
								</div>
							</form>
															        <div class="col-md-12">
                            <?php
                            if (mysqli_num_rows($followresultss) > 0) {
                                ?>

                                <table class="table table-responsive table-stripped table-bordered">
                                    <thead>
                                    <tr class='alert alert-warning'>
                                        <th>Sr.No</th>
                                       <th>Call Date Schedule</th>
                                        <th>Call Time Schedule</th>
                                        <th>Created On</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    $i = 0;
                                    while ($fuserrow = mysqli_fetch_object($followresultss)) {
                                        $i++;
                                        ?>
                                        <tr class="text-center">
                                            <td><?php echo $i; ?></td>
                                            <td class="text-left"><?php echo $fuserrow->call_scheduling ?></td>
                                            <td class="text-left"><?php echo $fuserrow->call_time_scheduling ?></td>
                                         
                                            <td><?php echo $fuserrow->created_on ?></td>
                                        </tr>
                                        <?php
                                    }
                                    ?>
                                    </tbody>
                                </table>
                                <?php
                            } else {
                                ?>
                                <div class='row'>
                                    <div class='col-md-12'>
                                        <div class="alert alert-danger">
                                            <strong>Warning!</strong> You have no Call Shedule for this lead.
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                            ?>
                        </div>

						</div>
					</div>
				</div>
			</section>
			<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
			<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
			<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
			<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
			<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

			<script>
				function openForm() {
					document.getElementById("myForm").style.display = "block";
				}

				function closeForm() {
					document.getElementById("myForm").style.display = "none";
				}
			</script>
			<script>
    var editor = CKEDITOR.replace('txtMessage');
</script>

<form action="#" method="post" id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
             <center><h4 class="modal-title text-center" style="padding-right:95px;">Enter Subject and Message</h4></center>   
            </div>
            <div class="modal-body">
                <div class="row mtop10">
                    <div class="col-md-12">
                        <input type='textbox' name='txtSubject' id='txtSubject' placeholder="Enter Subject" class="form-control"/>
                        <input type='hidden' name='txtemail' id='<?php echo $memberrow->profile_email ?>' placeholder="email" class="form-control"/>
                    </div>
                </div>
                <div class="row mtop10" style="padding-top:15px;">
                    <div class="col-md-12">
                        <textarea style="height: 200px; padding-top:15px;" id="txtMessage" name="txtMessage" placeholder="Enter Your Message" class="form-control"></textarea>
                    </div>
                </div>
                <div class="row mtop10">
                    <!--div class="col-md-5 text-center">
                        <input type="checkbox" value='1' checked="checked" id="btnIsHeader" name="btnIsHeader"/>&nbsp;<label for="btnIsHeader">Use Default template </label>
                    </div-->
                    <div class="col-md-7 text-center" style="padding-top:15px;">
                        <!--input type="button" id="btnSave" name="btnSave" value="Send Emails" class="btnCustom"/-->
                        <input type="submit" id="btnSaveMembers" name="btnSaveMembers" value="Send Email" class="btn btn-info"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<!-- Modal -->

<script>

    $('#div_error').hide();
    $('#div_error').html("");

    function checkContactNumber() {

        $('#div_error').hide();
        $('#div_error').html("");

        var txtcontact = $('#txtcontact').val();

        var lead_id = '<?php echo $memberrow->lead_id; ?>';

        if ($.trim(txtcontact).length > 0) {

            $.ajax({
                url: 'common_ajax.php',
                type: 'POST',
                data: {"ajax_for": 'unique_contact', "contact_no": txtcontact, "lead_id": lead_id},
                datatype: 'html',
                success: function (result) {

                    if (result != "pass") {

                        $('#txtcontact').val("");
                        $('#div_error').html(result);
                        $('#div_error').show();
                    }
                }
            });
        }
    }

    $('#txtcontact').blur(function () {

        checkContactNumber();
    });

    function saveuser() {

        checkContactNumber();
        
        var txtcname = $('#txtcname').val();
        var txtcall = $('#txtcall').val();
        var txtName = $('#txtName').val();
        var txtMobile = $('#txtMobile').val();
        var ddlLeadAllocated = $('#ddlLeadAllocated').val();
        var txtAddress = $('#txtAddress').val();
        var txtRemarks = $('#txtRemarks').val();
        var txtCollege = $('#txtCollege').val();
        var txtDate = $('#txtDate').val();
        var txtLeadSource = $('#txtLeadSource').val();
        var ddlLeadStatus = $('#ddlLeadStatus').val();
        var txtYear = $('#txtYear').val();
        var txtemailid = $('#txtemailid').val();
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        var txtcontact = $('#txtcontact').val();

      //  if ($.trim(txtLeadSource).length == 0 || $.trim(ddlLeadStatus).length == 0 || $.trim(txtcall).length == 0 || $.trim(txtcname).length == 0 || $.trim(txtcontact).length == 0 || $.trim(txtemailid).length == 0) {
             if ($.trim(txtLeadSource).length == 0 || $.trim(ddlLeadStatus).length == 0 || $.trim(txtcname).length == 0 || $.trim(txtcontact).length == 0 || $.trim(txtemailid).length == 0) {
            
            alert("Please fill all the required fields.");
            return false;
        }
        else if (emailReg.test(txtemailid) == false) {
            alert("Enter the valid email");
            return false;
        }
        else {
            return confirm('Are You Sure?');
        }
    }

    function back(param) {
        var c = confirm('Are You Sure');
        if (c == true && param == 0) {
            window.location = "manage-leads.php";
        }
        else if (c == true) {
            window.location = "manage-rishta-leads.php";
        }
        else {
            return c;
        }
    }

    function isDecimal(evt, element) {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if ((charCode != 46 || $(element).val().indexOf('.') != -1) &&      // “.” CHECK DOT, AND ONLY ONE.
            (charCode < 48 || charCode > 57))
            return false;
        return true;
    }

    function isNumber(evt, element) {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if ((charCode < 48 || charCode > 57))
            return false;
        return true;
    }

    $(document).ready(function () {
    
    
        $('body').on("keypress", '#txtYear', function () {
            return isNumber(event, this)
        });

        //$("#txtDate").datepicker({
          //  dateFormat: 'yy-mm-dd',
            // minDate: 0, // 0 days offset = today
        //});

        $('#txtName').keypress(function (e) {
            var regex = new RegExp("^[a-zA-Z ]+$");
            var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
            if (regex.test(str)) {
                return true;
            }

            e.preventDefault();
            return false;
        });
        //   $('input').bind("cut copy paste", function (e) {
        //       e.preventDefault();
        //   });

        $('#call_time_scheduling').timepicker({
            timeFormat: "hh:mm tt"
        });
    });
</script>
<script>

$(document).ready(function () {

    // Fix Country
    let country = "<?php echo htmlspecialchars($memberrow->country); ?>";

    if (country !== '') {

        $('#countryId')
            .val(country)
            .trigger('change');

    }

});

</script>

<script>

$(document).ready(function () {

    let country = "<?php echo trim($memberrow->country); ?>";
    let state   = "<?php echo trim($memberrow->state); ?>";
    let city    = "<?php echo trim($memberrow->city); ?>";

    // COUNTRY
    if (country !== '') {

        setTimeout(function () {

            $('#countryId')
                .val(country)
                .trigger('change');

            // WAIT FOR STATES TO LOAD
            setTimeout(function () {

                if (state !== '') {

                    $('#stateId')
                        .val(state)
                        .trigger('change');

                }

                // WAIT FOR CITIES TO LOAD
                setTimeout(function () {

                    if (city !== '') {

                        $('#cityId')
                            .val(city)
                            .trigger('change');

                    }

                }, 2500);

            }, 2500);

        }, 1500);

    }

    // Lead Status
    let leadStatus = $('#ddlLeadStatus').val();

    if (leadStatus !== '') {

        $('#ddlLeadStatus')
            .trigger('change');

    }

    // Lead Source
    let leadSource = $('#txtLeadSource').val();

    if (leadSource !== '') {

        $('#txtLeadSource')
            .trigger('change');

    }

});

</script>

<script>

$(document).ready(function () {

    $('#ddlLeadStatus').select2();

    $('#txtLeadSource').select2();

    $('#ddlLeadStatus').val(
        "<?php echo trim($memberrow->disposition); ?>"
    ).trigger('change');

    $('#txtLeadSource').val(
        "<?php echo trim($memberrow->source); ?>"
    ).trigger('change');

});

</script>

	<script>
		
		function saveusers()
		{
			var txtFollowup=$('#txtFollowup').val();
			var txtFollowupTakenOn=$('#txtFollowupTakenOn').val();
			
			if($.trim(txtFollowupTakenOn).length==0 || $.trim(txtFollowup).length==0)
			{
				alert("Please fill all the required fields.");
				return false;
			}
			else
			{
				return confirm('Are You Sure?');
			}
		}
		
		function back() 
		{
			var c=confirm('Are You Sure');
			if(c==true)
			{
				window.location="manage-leads.php";
			}
		}  	
		  
		$(document).ready(function() 
		{
			$("#txtFollowupTakenOn").datepicker({
				dateFormat: 'yy-mm-dd',
				// minDate: 0, // 0 days offset = today	
			});
			
		
		});	
	</script>
	
	<script src="include/ckeditor.js"></script>
	
	<script>
(function () {

    // --- Read the scheduled call date + time from the form ---
    var callDate = document.getElementById('txtcall')
                        ? document.getElementById('txtcall').value : '';
    var callTime = document.getElementById('call_time_scheduling')
                        ? document.getElementById('call_time_scheduling').value : '';

    if (!callDate || !callTime) return; // nothing scheduled, stop

    // Build a JS Date from "YYYY-MM-DD" + "HH:MM"
    var scheduledTime = new Date(callDate + 'T' + callTime + ':00');

    if (isNaN(scheduledTime.getTime())) return; // invalid date, stop

    var alreadyFired  = false;
    var beepCount     = 0;
    var maxBeeps      = 3;

    // --- Request browser notification permission on page load ---
    if ('Notification' in window && Notification.permission === 'default') {
        Notification.requestPermission();
    }

    // --- Beep using Web Audio API (no external file needed) ---
    function playBeep() {
        try {
            var ctx  = new (window.AudioContext || window.webkitAudioContext)();
            var osc  = ctx.createOscillator();
            var gain = ctx.createGain();

            osc.connect(gain);
            gain.connect(ctx.destination);

            osc.type      = 'sine';
            osc.frequency.value = 880; // Hz — change for different pitch
            gain.gain.value     = 0.6;

            osc.start();
            osc.stop(ctx.currentTime + 0.5); // 0.5 second beep

            osc.onended = function () { ctx.close(); };
        } catch (e) {
            console.warn('Audio beep failed:', e);
        }
    }

    // --- Show browser notification ---
    function showNotification() {
        if ('Notification' in window && Notification.permission === 'granted') {
            new Notification('📞 Rishta Depot — Call Reminder', {
                body: 'Time to call your lead! Scheduled call time has arrived.',
                icon: 'https://rishtasite.com/assets/images/logo-black.png'
            });
        }
    }

    // --- Fire alert: beep 3 times, 1 second apart ---
    function fireAlert() {
        if (alreadyFired) return;
        alreadyFired = true;

        showNotification();

        var beepInterval = setInterval(function () {
            if (beepCount >= maxBeeps) {
                clearInterval(beepInterval);
                return;
            }
            playBeep();
            beepCount++;
        }, 1000); // 1 second between beeps
    }

    // --- Check every 30 seconds if it's time ---
    var checker = setInterval(function () {

        var now = new Date();

        // Trigger if current time is within 30 seconds AFTER scheduled time
        var diff = now - scheduledTime; // milliseconds
        if (diff >= 0 && diff < 30000) {
            fireAlert();
            clearInterval(checker); // stop checking after firing
        }

        // Stop checking after 1 hour past scheduled time
        if (diff > 3600000) {
            clearInterval(checker);
        }

    }, 30000);

    // Also check immediately on page load (in case page opened late)
    (function immediateCheck() {
        var now  = new Date();
        var diff = now - scheduledTime;
        if (diff >= 0 && diff < 60000) { // within 60s of scheduled time
            fireAlert();
            clearInterval(checker);
        }
    })();

})();
</script>

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