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

        <!-- ==================================================== -->
        <!-- Start right Content here -->
        <!-- ==================================================== -->
        <!-- Loader -->
        <div id="loader-overlay" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(255,255,255,0.8); z-index:1050; text-align:center;">
            <div class="spinner-border text-primary" role="status" style="margin-top:20%;">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">Uploading and processing, please wait...</p>
        </div>
        
        <style>
            #loader-overlay {
                display: none;
                position: fixed;
                z-index: 2000;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255,255,255,0.85);
                display: flex;
                justify-content: center;
                align-items: center;
                flex-direction: column;
            }
        </style>


        <div class="page-content">

            <!-- Start Container Fluid -->
            <div class="container-fluid">

                <!-- ========== Page Title Start ========== -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <h4 class="mb-0 fw-semibold">Users</h4>
                            <ol class="breadcrumb mb-0">
                                <li class="breadcrumb-item"><a href="javascript: void(0);">Users</a></li>
                                <li class="breadcrumb-item active">List</li>
                            </ol>
                        </div>
                    </div>
                </div>
                <!-- ========== Page Title End ========== -->
				
				<div class="row">
                         <div class="col-lg-12">
                              <div class="card">
                                   <div class="card-header border-0">
                                        <div class="row justify-content-between">
                                             <div class="col-lg-6">
                                                  <div class="row align-items-center">
                                                       <!--div class="col-lg-6">
                                                            <form class="app-search d-none d-md-block me-auto">
                                                                 <div class="position-relative">
                                                                      <input type="search" class="form-control" placeholder="Search Agent" autocomplete="off" value="">
                                                                      <iconify-icon icon="solar:magnifer-broken" class="search-widget-icon"></iconify-icon>
                                                                 </div>
                                                            </form>
                                                       </div-->
                                                       <!--div class="col-lg-4">
                                                            <h5 class="text-dark fw-medium mb-0">311 <span class="text-muted"> Agent</span></h5>
                                                       </div-->
                                                  </div>
                                             </div>
                                             <div class="col-lg-6">
                                                  <div class="text-md-end mt-3 mt-md-0">
                                                       <!--button type="button" class="btn btn-outline-primary me-1"><i class="ri-settings-2-line me-1"></i>More Setting</button-->
                                                       <!--button type="button" class="btn btn-outline-primary me-1"><i class="ri-filter-line me-1"></i> Filters</button-->
                                                       <button type="button" class="btn btn-success me-1" data-bs-toggle="modal" data-bs-target="#exampleModalXl"><i class="ri-add-line"></i> New Import</button>
										
                                                  </div>
                                             </div><!-- end col-->
                                        </div>
                                   </div>
                              </div>
                         </div>
                    </div> 
					
					<!-- Modal -->
					<div class="modal fade" id="exampleModalXl" tabindex="-1" aria-labelledby="exampleModalXlLabel" aria-hidden="true">
						<div class="modal-dialog modal-xl">
							<div class="modal-content">
								<div class="modal-header">
									<h5 class="modal-title h4" id="exampleModalXlLabel">CSV Import</h5>
									<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								</div>
								<div class="modal-body">
									<ul class="nav nav-tabs">
    <li class="nav-item">
        <a href="#home" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
            <span class="d-block d-sm-none"><i class="bx bx-home"></i></span>
            <span class="d-none d-sm-block">Lead Upload</span>
        </a>
    </li>
    <!--li class="nav-item">
        <a href="#profile" data-bs-toggle="tab" aria-expanded="true" class="nav-link active">
            <span class="d-block d-sm-none"><i class="bx bx-user"></i></span>
            <span class="d-none d-sm-block">Profile</span>
        </a>
    </li>
    <li class="nav-item">
        <a href="#messages" data-bs-toggle="tab" aria-expanded="false" class="nav-link">
            <span class="d-block d-sm-none"><i class="ri-mail-line"></i></span>
            <span class="d-none d-sm-block">Messages</span>
        </a>
    </li-->
</ul>
<div class="tab-content text-muted">
    <div class="tab-pane show active" id="home">
            <h2>Upload CSV File</h2>

    <form action="#" method="POST" enctype="multipart/form-data">
        <label for="csv_file" class="form-label">Choose CSV file:</label>
        <input type="file" name="csv_file" id="csv_file" class="form-control" required>
        <button type="submit" name="submit" class="btn btn-primary">Upload</button>
    </form>

    </div>
    <!--div class="tab-pane show active" id="profile">
        <p class="mb-0">Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc,
            litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules.
            Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser
            necessi far uniform grammatica, pronunciation e plu sommun paroles. Ma quande lingues coalesce, li grammatica del resultant
            lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam
            li existent Europan lingues.
        </p>
    </div>
    <div class="tab-pane" id="messages">
        <p class="mb-0">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
            totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
            Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui
            ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
            velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem?
        </p>
    </div-->
</div>
								</div>
							</div>
						</div>
					</div>
					

                <div class="row">
                    <div class="col-xl-12">
                        <div class="card">
						
                            <div class="card-body">
                                <div>
                                    <div class="py-3">
                                        <div id="table-gridjs"></div>
                                    </div>
                                     

									 
                                    <div class="">
                                        <!--div class="highlight-toolbar border-top-0">
                                            <ul class="nav nav-pills">
                                                <li class="nav-item">
                                                    <a href="#gridjs-basic-html" data-bs-toggle="tab" aria-expanded="false" class="nav-link active">
                                                        <span class="fs-12 text-uppercase">html</span>
                                                    </a>
                                                </li>
                                                <li class="nav-item">
                                                    <a href="#gridjs-basic-javascript" data-bs-toggle="tab" aria-expanded="true" class="nav-link">
                                                        <span class="fs-12 text-uppercase">javascript</span>
                                                    </a>
                                                </li>
                                            </ul>
                                            <button class="btn btn-sm btn-outline-success btn-copy-clipboard" data-clipboard-action="copy">Copy</button>
                                        </div-->
                                        <div class="tab-content">
                                            <div class="tab-pane show active" id="gridjs-basic-html">
                                                <!--div class="code">
                                                    <pre class="language-html">
                                                        <code>
                                                            &lt;div id=&quot;table-gridjs&quot;&gt;&lt;/div&gt;
                                                        </code>
                                                    </pre>
                                                </div-->
                                            </div>
                                            <div class="tab-pane" id="gridjs-basic-javascript">
                                                <!--div class="code">
                                                    <pre class="language-javascript">
                                                    <code>
                                                        // Basic Table
                                                        if (document.getElementById("table-gridjs"))
                                                             new gridjs.Grid({
                                                                  columns: [{
                                                                       name: 'ID',
                                                                       formatter: (function (cell) {
                                                                            return gridjs.html('<span class="fw-semibold">' + cell + '</span>');
                                                                       })
                                                                  },
                                                                       "Name",
                                                                  {
                                                                       name: 'Email',
                                                                       formatter: (function (cell) {
                                                                            return gridjs.html('<a href="#">' + cell + '</a>');
                                                                       })
                                                                  },
                                                                       "Position", "Company", "Country",
                                                                  {
                                                                       name: 'Actions',
                                                                       width: '120px',
                                                                       formatter: (function (cell) {
                                                                            return gridjs.html("<a href='#' class='text-reset text-decoration-underline'>" + "Details" + "</a>");
                                                                       })
                                                                  },
                                                                  ],
                                                                  pagination: {
                                                                       limit: 5
                                                                  },
                                                                  sort: true,
                                                                  search: true,
                                                                  data: [
                                                                       ["11", "Alice", "alice@example.com", "Software Engineer", "ABC Company", "United States"],
                                                                       ["12", "Bob", "bob@example.com", "Product Manager", "XYZ Inc", "Canada"],
                                                                       ["13", "Charlie", "charlie@example.com", "Data Analyst", "123 Corp", "Australia"],
                                                                       ["14", "David", "david@example.com", "UI/UX Designer", "456 Ltd", "United Kingdom"],
                                                                       ["15", "Eve", "eve@example.com", "Marketing Specialist", "789 Enterprises", "France"],
                                                                       ["16", "Frank", "frank@example.com", "HR Manager", "ABC Company", "Germany"],
                                                                       ["17", "Grace", "grace@example.com", "Financial Analyst", "XYZ Inc", "Japan"],
                                                                       ["18", "Hannah", "hannah@example.com", "Sales Representative", "123 Corp", "Brazil"],
                                                                       ["19", "Ian", "ian@example.com", "Software Developer", "456 Ltd", "India"],
                                                                       ["20", "Jane", "jane@example.com", "Operations Manager", "789 Enterprises", "China"]
                                                                  ]
                                                             }).render(document.getElementById("table-gridjs"));
                                                    </code>
                                                </pre>
                                                </div-->
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                    </div> <!-- end card body -->

                   


                </div> <!-- end row -->

            </div>
            <!-- End Container Fluid -->
<script>

$(document).ready(function() {
    if (document.getElementById("table-gridjs")) {
        new gridjs.Grid({
            columns: [{
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            }, "File Name", {
                name: "Uploaded Date",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + "</a>")
                }
            }, "Import By", "Status", "Uploaded","Not Uploaded"
			],
            pagination: {
                limit: 5
            },
            sort: true,
            search: true,
            server: {
                url: '<?php echo $base_url;?>fetch-lead-import-user.php',  // The PHP script that fetches data
                then: data => data,     // Process the fetched data
                // You can handle any other server-side processing here if necessary
            }
        }).render(document.getElementById("table-gridjs"));
    }
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.querySelector('form');
    form.addEventListener('submit', function () {
        document.getElementById('loader-overlay').style.display = 'block';
    });
});
</script>

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

 <?php

// Check if the form is submitted
if (isset($_POST['submit'])) {
    // Check if a file is uploaded
    if ($_FILES['csv_file']['error'] == 0) {
        // Get the file details
        $file_name = $_FILES['csv_file']['name'];
        $file_tmp = $_FILES['csv_file']['tmp_name'];
        // Open the file for reading
        if (($handle = fopen($file_tmp, "r")) !== FALSE) {
            // Skip the header row if your CSV file has a header
            fgetcsv($handle);  // Skip the first row of the CSV file
            $success_enquiry = "";
		    $ussccuss_enquiry = "";
		    $scs_lead_count=0;   // successfully upload lead count
		    $unscs_lead_count=0; // failed to upload lead count
		    $duplicate_lead_count=0; // failed to upload lead count
            
            // Loop through each row in the CSV file
            while (($data = fgetcsv($handle)) !== FALSE) {
                // Extract each column from the CSV file
                $name = $data[1];
                $email = $data[2];
                $mobile_no = $data[3];
                $source_code = $data[4];
				$project = $data[5];
				$intent = $data[6];
				$status = $data[7];
				$assigned_user = $data[8];
                $created_date = $data[9];
                // Remove ordinal suffixes using regex
                $cleaned = preg_replace('/\b(\d+)(st|nd|rd|th)\b/', '$1', $created_date);
                
                // Convert to datetime
                $date = DateTime::createFromFormat('g:i a, F j Y', $cleaned);
                if ($date) {
                    $formatted = $date->format('Y-m-d h:i:s A'); // e.g. 2025-03-31 05:57:00 PM
                    
                } else {
                    $formatted = date('Y-m-d h:i:s A');
                }
                
                $p_detail = mysqli_fetch_array(mysqli_query($conn,"select * from tbl_project where tbl_project_code='".$project."' and tbl_project_flag=0"));
                                // Sanitize the inputs (optional, for security)
                $project_name = $conn->real_escape_string($p_detail['tbl_project_name']);
                $project_id = $conn->real_escape_string($p_detail['tbl_project_id']);

		        $check_profile=mysqli_num_rows(mysqli_query($conn,"Select tbl_lead_user_profile_id from tbl_lead_user_profile where 1 and tbl_lead_user_profile_flag=0 and tbl_lead_user_profile_mobile='".$mobile_no."'"));
        		if(!$check_profile){
        			$sql="insert into tbl_lead_user_profile set tbl_lead_user_profile_name='".$name."',tbl_lead_user_profile_email='".$email."',tbl_lead_user_profile_mobile='".$mobile_no."',tbl_lead_user_profile_cdate='".$formatted."',tbl_lead_user_profile_flag=0,tbl_lead_user_profile_cuser='ADMIN'";
        			$result=mysqli_query($conn,$sql);
        			$user_profile_id=$conn->insert_id;
        			if($result){
        				//$source_name=get_source_name($_POST['lead_source']);
        				$sorce_detail=mysqli_fetch_array(mysqli_query($conn,"select tbl_lead_source_id, source_name  from tbl_lead_source where 1 and flag=0 and source_code='".$source_code."'"));
                        $source_id = $conn->real_escape_string($sorce_detail['tbl_lead_source_id']);
                        $source_name = $conn->real_escape_string($sorce_detail['source_name']);
                        
                        $auser_detail=mysqli_fetch_array(mysqli_query($conn,"select id, name  from tbl_invite_user where 1 and flag=0 and name='".$assigned_user."'"));
                        $a_id = $conn->real_escape_string($auser_detail['id']);
                        $a_name = $conn->real_escape_string($auser_detail['name']);
                        
                        if($status =='' || $status =='new' || $status =='New' || $status =='NEW'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else if($status == 'Not Connected'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_fdate='".$formatted."',tbl_lead_user_status='Not Connected',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                    		    	
                        }
                        else if($status == 'In Progress'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_fdate='".$formatted."',tbl_lead_user_status='In Progress',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else if($status == 'SV Scheduled'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_fdate='".$formatted."',
                    		    	tbl_lead_user_sv_date='".$formatted."',tbl_lead_user_sv_type='OnSite',tbl_lead_user_status='SV Scheduled',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else if($status == 'SV Completed'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_fdate='".$formatted."',
                    		    	tbl_lead_user_sv_date='".$formatted."',tbl_lead_user_sv_duration='1 hr',tbl_lead_user_status='SV Completed',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else if($status == 'Booking Completed'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_booking_date='".$formatted."',tbl_lead_user_status='Booking Completed',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else if($status == 'Dead Lead'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_status='Dead Lead',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else if($status == 'EOI Completed'){
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_eoi_date='".$formatted."',tbl_lead_user_status='EOI Completed',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        else{
                            $sql="insert into tbl_lead_user set tbl_lead_user_profile_id='".$user_profile_id."',tbl_lead_user_mobile='".$mobile_no."',
                    		    	tbl_lead_user_assigned_date='".date('Y-m-d H:i:s')."',tbl_lead_user_source_id='".$source_id."',tbl_lead_user_source_name='".$source_name."',
                    		    	tbl_lead_user_assigned_user_id='".$a_id."',tbl_lead_user_regdate='".$formatted."',tbl_lead_user_project_id='".$project_id."',
                    		    	tbl_lead_user_intent='".$intent."',tbl_lead_user_cdate='".date('Y-m-d H:i:s')."',tbl_lead_user_flag=0,
                    		    	tbl_lead_user_cuser='ADMIN'";
                        }
                        
        		    	
        				//$lead_result=mysqli_query($conn,$sql);
        				
        				if(mysqli_query($conn,$sql)){
        				    $lead_id=$conn->insert_id;
        				    if (isset($project)) {
        				        if($status =='' || $status =='new' || $status =='New' || $status =='NEW'){
                                    $sql_followup="";
                                }
                                else if($status == 'Not Connected'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 1,
                                                    tbl_subfollowup_status_name = 'Not Connected',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_date = '$formatted',
                                                    tbl_subfollowup_intent = '$intent',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_project_id = $project_id,
                                                    tbl_subfollowup_flag = 0";
                            		    	
                                }
                                else if($status == 'In Progress'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 2,
                                                    tbl_subfollowup_status_name = 'In Progress',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_date = '$formatted',
                                                    tbl_subfollowup_intent = '$intent',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_project_id = $project_id,
                                                    tbl_subfollowup_flag = 0";
                                }
                                else if($status == 'SV Scheduled'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 3,
                                                    tbl_subfollowup_status_name = 'SV Scheduled',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_date = '$formatted',
                                                    tbl_subfollowup_intent = '$intent',
                                                    tbl_subfollowup_sv_scheduled_date = '$formatted',
                                                    tbl_subfollowup_sv_type = 'On Site',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_project_id = $project_id,
                                                    tbl_subfollowup_flag = 0";
                                }
                                else if($status == 'SV Completed'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 4,
                                                    tbl_subfollowup_status_name = 'SV Completed',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_date = '$formatted',
                                                    tbl_subfollowup_sv_intent = '$intent',
                                                    tbl_subfollowup_sv_scheduled_date = '$formatted',
                                                    tbl_subfollowup_sv_type = 'On Site',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_project_id = $project_id,
                                                    tbl_subfollowup_flag = 0";
                                }
                                else if($status == 'Booking Completed'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 5,
                                                    tbl_subfollowup_status_name = 'Booking Completed',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_date = '$formatted',
                                                    tbl_subfollowup_booking_date = '$formatted',
                                                    tbl_subfollowup_booking_net_purchase_price = '0',
                                                    tbl_subfollowup_booking_amt_paid = '0',
                                                    tbl_subfollowup_booking_unit_no = '0',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_project_id = $project_id,
                                                    tbl_subfollowup_flag = 0";
                                }
                                else if($status == 'Dead Lead'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 6,
                                                    tbl_subfollowup_status_name = 'Dead Lead',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_project_id = $project_id,
                                                    tbl_subfollowup_flag = 0";
                                }
                                else if($status == 'EOI Completed'){
                                    $sql_followup="INSERT INTO tbl_subfollowup SET 
                                                    tbl_subfollowup_status_id = 7,
                                                    tbl_subfollowup_status_name = 'EOI Completed',
                                                    tbl_lead_user_id = '$lead_id',
                                                    tbl_subfollowup_date = '$formatted',
                                                    tbl_subfollowup_eoi_token_date = '$formatted',
                                                    tbl_subfollowup_eoi_token_amount = '$token_amount',
                                                    tbl_subfollowup_eoi_validity_date = '$formatted',
                                                    tbl_subfollowup_eoi_unit_price= '0',
                                                    tbl_subfollowup_eoi_unit_no= '0',
                                                    tbl_subfollowup_cdate = '".date('Y-m-d H:i:s')."',
                                                    tbl_subfollowup_flag = 0";
                                }
                                else{
                                    $sql_followup="";
                                }
                                
                                if($sql_followup !=""){
                                    mysqli_query($conn, $sql_followup);
                                }
                                // Insert Data
                                $sql = "INSERT INTO tbl_lead_user_projects (tbl_lead_user_id, tbl_lead_user_prj_id,tbl_lead_user_projects_name) VALUES ('$lead_id', '".$project_id."','". $project_name. "')";
                                mysqli_query($conn, $sql);
                                
        				    }
        				    $scs_lead_count++;
        				    if ($success_enquiry == '') {
									$success_enquiry = $mobile_no;
							} else {
								$success_enquiry = $success_enquiry . ',' . $mobile_no;
							}
							
        				}else{
        					$sql=mysqli_query($conn,"DELETE FROM tbl_lead_user_profile WHERE tbl_lead_user_profile_id='".$user_profile_id."'");
        					$unscs_lead_count++;
        					if ($ussccuss_enquiry == '') {
								$ussccuss_enquiry = $mobile_no;
							} else {
								$ussccuss_enquiry = $ussccuss_enquiry . ',' . $mobile_no;
							}
        			
        				}
        			}
        		}else{
        			//$check_profile=mysqli_fetch_array(mysqli_query($conn,"Select tbl_lead_user_profile_id from tbl_lead_user_profile where 1 and tbl_lead_user_profile_flag=0 and tbl_lead_user_profile_mobile='".$mobile_no."'"));
        			$check_lead=mysqli_fetch_array(mysqli_query($conn,"Select tbl_lead_user_id , tbl_lead_user_lead_count from tbl_lead_user where 1 and tbl_lead_user_flag=0 and tbl_lead_user_mobile='".$mobile_no."'"));
        			if($check_lead){
        			    $check_lead_count=$check_lead['tbl_lead_user_lead_count'] +1;
        			    //$source_name=get_source_name($_POST['lead_source']);
            		    $sql="update tbl_lead_user set tbl_lead_user_lead_count='".$check_lead_count."', tbl_lead_user_edate='".date('Y-m-d h:i:s A')."' where tbl_lead_user_id='".$check_lead['tbl_lead_user_id']."'";
            			$lead_result=mysqli_query($conn,$sql);
            			if($lead_result){
        				    $duplicate_lead_count++;
            			}else{
            				// do nothing
            			}
        			}
        			else{
        			    // do nothing
        			}
        			
        		}
	        } // while loop close
			
			
			
			 if ($success_enquiry != '') {
			     $insert_lead_import=mysqli_query($conn,"Insert into  tbl_lead_import set tbl_lead_import_filename='CSV File',tbl_lead_import_upload_date='".date('Y-m-d H:i:s')."',
			     tbl_lead_import_imported_by='ADMIN',tbl_lead_import_status='Uploaded',tbl_lead_import_uploaded='".$scs_lead_count."',	tbl_lead_import_not_uploaded='".$unscs_lead_count."',
				tbl_lead_import_duplicate='". $duplicate_lead_count ."' ");
			
				$msg = "Request Completed. Success:" . $success_enquiry . " Unsuccess:" . $ussccuss_enquiry;
					echo "<script>
                            Swal.fire({
                                title: 'Success!',
                                text: 'Request Completed.',
                                icon: 'success',
                                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                                buttonsStyling: false,
                                showCloseButton: false
                            }).then(function() {
                                window.location.href = 'lead-import-list.php';
                            });
                        </script>";
			}
			else{
			    echo "<script>
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed To upload Lead Either Duplicate.Success:" . $success_enquiry . " Unsuccess:" . $ussccuss_enquiry."',
                        icon: 'error',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false,
                        showCloseButton: false
                    }).then(function() {
                        window.location.href = 'lead-import-list.php';
                    });
                </script>";
			}
            }
        }
   
    }
    
?>