<?php
$msg = '';
include("include/settings.php");
include("checksession.php");

$where = '';
$condition = '';

$skip = 0;
if (isset($_POST['page_skip'])) {
    $skip = $_POST['page_skip'] * 100 - 100;
} else {
    $_POST['page_skip'] = 0;
}

$pass = 0;

if (isset($_POST['ddlUserId']) && trim($_POST['ddlUserId']) != 0) {
    $pass = 1;
} else if (isset($_POST['ddlLeadType']) && trim($_POST['ddlLeadType']) != 0) {
    $pass = 1;
} else if (isset($_POST['txtFromDate']) && trim($_POST['txtFromDate']) != null) {
    $pass = 1;
} else if (isset($_POST['txtToDate']) && trim($_POST['txtToDate']) != null) {
    $pass = 1;
} else if (isset($_POST['txtSearch']) && trim($_POST['txtSearch']) != null) {
    $pass = 1;
} else if (isset($_POST['countryId']) && trim($_POST['countryId']) != null) {
    $pass = 1;
} else if (isset($_POST['stateId']) && trim($_POST['stateId']) != null) {
    $pass = 1;
} else if (isset($_POST['cityId']) && trim($_POST['cityId']) != null) {
    $pass = 1;
} else if (isset($_POST['searchGender']) && trim($_POST['searchGender']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMemberStatus']) && trim($_POST['searchMemberStatus']) != null) {
    $pass = 1;
} else if (isset($_POST['searchCaste']) && trim($_POST['searchCaste']) != null) {
    $pass = 1;
} else if (isset($_POST['searchResidencyStatus']) && trim($_POST['searchResidencyStatus']) != null) {
    $pass = 1;
} else if (isset($_POST['searchCurrency']) && trim($_POST['searchCurrency']) != null) {
    $pass = 1;
} else if (isset($_POST['searchDisposition']) && trim($_POST['searchDisposition']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMinAge']) && trim($_POST['searchMinAge']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMaxAge']) && trim($_POST['searchMaxAge']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMinFootHeight']) && trim($_POST['searchMinFootHeight']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMinInchHeight']) && trim($_POST['searchMinInchHeight']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMaxFootHeight']) && trim($_POST['searchMaxFootHeight']) != null) {
    $pass = 1;
} else if (isset($_POST['searchMaxInchHeight']) && trim($_POST['searchMaxInchHeight']) != null) {
    $pass = 1;
}else if (isset($_POST['religion']) && trim($_POST['religion']) != null) {
    $pass = 1;
}else if (isset($_POST['source']) && trim($_POST['source']) != null) {
    $pass = 1;
}else if (isset($_POST['touched']) && trim($_POST['touched']) != null) {
    $pass = 1;
} 
else {
    $pass = 0;
}


if ($pass == 1) {

if (isset($_POST['ddlLeadType']) && !empty($_POST['ddlLeadType'])) {
    $selectedLeadTypes = $_POST['ddlLeadType'];

    // Initialize an empty array to store the conditions for selected lead types
    $leadTypeConditions = [];

    // Loop through the selected lead types and construct conditions for each
    foreach ($selectedLeadTypes as $selectedType) {
        // Handle each selected lead type as needed
        switch ($selectedType) {
            case 1:
                $leadTypeConditions[] = "disposition LIKE '%New Call%'";
                break;
            case 2:
                $leadTypeConditions[] = "disposition LIKE '%No match shared yet%'";
                break;
            case 3:
                $leadTypeConditions[] = "disposition LIKE '%Match Shared%'";
                break;
            case 4:
                $leadTypeConditions[] = "disposition LIKE '%Follow up%'";
                break;
            case 5:
                $leadTypeConditions[] = "disposition LIKE '%Close to Conversion%'";
                break;
            case 6:
                $leadTypeConditions[] = "disposition LIKE '%Fully Paid%'";
                break;
            case 7:
                $leadTypeConditions[] = "disposition LIKE '%Lead Rejected%'";
                break;
            case 8:
                $leadTypeConditions[] = "disposition LIKE '%Refund%'";
                break;
            case 9:
                $leadTypeConditions[] = "disposition LIKE '%Fresh Lead%'";
                break;
            case 10:
                $leadTypeConditions[] = "disposition LIKE '%Renewal Lead%'";
                break;
            case 11:
                $leadTypeConditions[] = "disposition LIKE '%Ptential CRM Lead%'";
                break;
            case 12:
                $leadTypeConditions[] = "disposition LIKE '%Interested%'";
                break;
            case 13:
                $leadTypeConditions[] = "disposition LIKE '%Expired (Not to be converted)%'";
                break;
            case 14:
                $leadTypeConditions[] = "disposition LIKE '%Inactive%'";
                break;
            case 15:
                $leadTypeConditions[] = "disposition LIKE '%Ringing%'";
                break;
            case 16:
                $leadTypeConditions[] = "disposition LIKE '%Expired%'";
                break;
            case 17:
                $leadTypeConditions[] = "disposition LIKE '%Active%'";
                break;
            case 18:
                $leadTypeConditions[] = "disposition LIKE '%Wrong Number%'";
                break;
            case 19:
                $leadTypeConditions[] = "disposition LIKE '%On Hold%'";
                break;
            case 20:
                $leadTypeConditions[] = "disposition LIKE '%Confirmed Rishta done%'";
                break;
            case 21:
                $leadTypeConditions[] = "disposition LIKE '%Old Leads%'";
                break;
            // Add cases for other lead types as needed
            default:
   $leadTypeConditions[] = "disposition LIKE '%New Call%'";
                
        }
    }

    // Join the conditions using OR to create a single condition
    $leadTypeCondition = implode(' OR ', $leadTypeConditions);

    // Append the lead type condition to the overall condition
    
    $condition .= "      (" . $leadTypeCondition . ") AND ";
    //        $condition .= trim($condition) != null ? ' AND (' . $leadTypeCondition . ')' : '(' . $leadTypeCondition . ')';

}


if (trim($_POST['touched']) != null) {
    $touched = trim($_POST['touched']);
    
    switch ($touched) {
        case 'today':
            $fromDate = date('Y-m-d'); // Today's date
            $condition .= " lead_created_on >= '{$fromDate}' ";
            break;
            
        case 'yesterday':
            $fromDate = date('Y-m-d', strtotime('-1 day')); // Yesterday's date
            $toDate = date('Y-m-d'); // Today's date
            $condition .= " lead_created_on >= '{$fromDate}' AND lead_created <= '{$toDate}' ";
            break;
            
        case 'this_week':
            $startOfWeek = date('Y-m-d', strtotime('monday this week')); // Start of the week
            $condition .= " lead_created_on >= '{$startOfWeek}' ";
            break;
            
        case 'this_month':
            $startOfMonth = date('Y-m-01'); // First day of the current month
            $condition .= " lead_created_on >= '{$startOfMonth}' ";
            break;
            
        default:
            case 'all':
            $startOfMonth = date('2020-01-01'); // First day of the current month
            $condition .= " lead_created >= '{$startOfMonth}' ";
            break;
       
    }
}












    if (trim($_POST['txtSearch']) != null) {
        $search_data = trim($_POST['txtSearch']);
        $condition .= trim($condition) != null ? ' and ' : ' ';
        $condition .= " (contact_no like '%{$search_data}%' or contact_no like '%{$search_data}%' or  email_id like '%{$search_data}%' or profile_name like '%{$search_data}%' or contact_name like '%{$search_data}%')";
    }

    if (trim($_POST['txtFromDate']) != null) {
        $fromdate = $_POST['txtFromDate'];
        $condition .= trim($condition) != null ? ' and ' : ' ';

        if (trim($_POST['txtFromDate']) != null) {
            $condition .= " lead_created_on >= '{$fromdate}' ";
        }
    }

    if (trim($_POST['txtToDate']) != null) {
        $todate = $_POST['txtToDate'];
        $condition .= trim($condition) != null ? ' and ' : ' ';

        if (trim($_POST['txtToDate']) != null) {
            $condition .= " lead_created_on <= '{$todate}' ";
        }
    }

if (isset($_POST['ddlUserId']) && !empty($_POST['ddlUserId'])) {
    $selectedExecutives = $_POST['ddlUserId'];

    // Initialize an empty array to store the conditions for selected executives
    $executiveConditions = [];

    // Loop through the selected executives and construct conditions for each
    foreach ($selectedExecutives as $selectedExecutive) {
        // Construct condition for each selected executive
        $executiveConditions[] = "lead_allocated_to = " . $selectedExecutive;
    }

    // Join the conditions using OR to create a single condition
    $executiveCondition = implode(' OR ', $executiveConditions);

    // Append the executive condition to the overall condition
    $condition .= " AND  (" . $executiveCondition . ")";
}


if (isset($_POST['countryId']) && !empty($_POST['countryId'])) {
    $selectedCountries = $_POST['countryId'];

    // Initialize an empty array to store the conditions for selected countries
    $countryConditions = [];

    // Loop through the selected countries and construct conditions for each
    foreach ($selectedCountries as $selectedCountry) {
        // Construct condition for each selected country
        $countryConditions[] = "country = '" . $selectedCountry . "'";
    }

    // Join the conditions using OR to create a single condition
    $countryCondition = implode(' OR ', $countryConditions);

    // Append the country condition to the overall condition
 //   $condition .= " AND (" . $countryCondition . ")";
        $condition .= trim($condition) != null ? ' AND (' . $countryCondition . ')' : '(' . $countryCondition . ')';
}


// Handling state conditions
if (isset($_POST['stateId']) && !empty($_POST['stateId'])) {
    $selectedStates = $_POST['stateId'];
    $stateConditions = [];

    foreach ($selectedStates as $selectedState) {
        // Construct conditions for each selected state
        $stateConditions[] = "state = '" . $selectedState . "'";
    }

    // Join conditions for states with OR
    $stateCondition = implode(' OR ', $stateConditions);

    // Append state conditions to overall condition
    $condition .= trim($condition) != null ? ' AND (' . $stateCondition . ')' : '(' . $stateCondition . ')';
}

// Handling city conditions
if (isset($_POST['cityId']) && !empty($_POST['cityId'])) {
    $selectedCities = $_POST['cityId'];
    $cityConditions = [];

    foreach ($selectedCities as $selectedCity) {
        // Construct conditions for each selected city
        $cityConditions[] = "city = '" . $selectedCity . "'";
    }

    // Join conditions for cities with OR
    $cityCondition = implode(' OR ', $cityConditions);

    // Append city conditions to overall condition
    $condition .= trim($condition) != null ? ' AND (' . $cityCondition . ')' : '(' . $cityCondition . ')';
}

if (isset($_POST['searchGender']) && !empty($_POST['searchGender'])) {
    $searchGender = $_POST['searchGender'];
    $genderConditions = [];

    foreach ($searchGender as $gender) {
        $genderConditions[] = "gender = '" . $gender . "'";
    }

    $genderCondition = implode(' OR ', $genderConditions);

    $condition .= trim($condition) != null ? ' AND (' . $genderCondition . ')' : '(' . $genderCondition . ')';
}

if (isset($_POST['searchMemberStatus']) && !empty($_POST['searchMemberStatus'])) {
    $searchMemberStatus = $_POST['searchMemberStatus'];
    $memberStatusConditions = [];

    foreach ($searchMemberStatus as $memberStatus) {
        $memberStatusConditions[] = "member_status = '" . $memberStatus . "'";
    }

    $memberStatusCondition = implode(' OR ', $memberStatusConditions);

    $condition .= trim($condition) != null ? ' AND (' . $memberStatusCondition . ')' : '(' . $memberStatusCondition . ')';
}

if (isset($_POST['searchCaste']) && !empty($_POST['searchCaste'])) {
    $searchCaste = $_POST['searchCaste'];
    $casteConditions = [];

    foreach ($searchCaste as $caste) {
        $casteConditions[] = "caste = '" . $caste . "'";
    }

    $casteCondition = implode(' OR ', $casteConditions);

    $condition .= trim($condition) != null ? ' AND (' . $casteCondition . ')' : '(' . $casteCondition . ')';
}

if (isset($_POST['searchResidencyStatus']) && !empty($_POST['searchResidencyStatus'])) {
    $searchResidencyStatus = $_POST['searchResidencyStatus'];
    $residencyStatusConditions = [];

    foreach ($searchResidencyStatus as $residencyStatus) {
        $residencyStatusConditions[] = "residency_status = '" . $residencyStatus . "'";
    }

    $residencyStatusCondition = implode(' OR ', $residencyStatusConditions);

    $condition .= trim($condition) != null ? ' AND (' . $residencyStatusCondition . ')' : '(' . $residencyStatusCondition . ')';
}

if (isset($_POST['searchCurrency']) && !empty($_POST['searchCurrency'])) {
    $searchCurrency = $_POST['searchCurrency'];
    $currencyConditions = [];

    foreach ($searchCurrency as $currency) {
        $currencyConditions[] = "currency = '" . $currency . "'";
    }

    $currencyCondition = implode(' OR ', $currencyConditions);

    $condition .= trim($condition) != null ? ' AND (' . $currencyCondition . ')' : '(' . $currencyCondition . ')';
}

if (isset($_POST['searchDisposition']) && !empty($_POST['searchDisposition'])) {
    $searchDisposition = $_POST['searchDisposition'];
    $dispositionConditions = [];

    foreach ($searchDisposition as $disposition) {
        $dispositionConditions[] = "disposition = '" . $disposition . "'";
    }

    $dispositionCondition = implode(' OR ', $dispositionConditions);

    $condition .= trim($condition) != null ? ' AND (' . $dispositionCondition . ')' : '(' . $dispositionCondition . ')';
}

if (isset($_POST['searchMinAge']) && !empty($_POST['searchMinAge'])) {
    $searchMinAge = $_POST['searchMinAge'];
    $minAgeConditions = [];

    foreach ($searchMinAge as $minAge) {
        $minAgeConditions[] = "age >= '" . $minAge . "'";
    }

    $minAgeCondition = implode(' OR ', $minAgeConditions);

    $condition .= trim($condition) != null ? ' AND (' . $minAgeCondition . ')' : '(' . $minAgeCondition . ')';
}

if (isset($_POST['searchMaxAge']) && !empty($_POST['searchMaxAge'])) {
    $searchMaxAge = $_POST['searchMaxAge'];
    $maxAgeConditions = [];

    foreach ($searchMaxAge as $maxAge) {
        $maxAgeConditions[] = "age <= '" . $maxAge . "'";
    }

    $maxAgeCondition = implode(' OR ', $maxAgeConditions);

    $condition .= trim($condition) != null ? ' AND (' . $maxAgeCondition . ')' : '(' . $maxAgeCondition . ')';
}

if (isset($_POST['searchMinFootHeight']) && !empty($_POST['searchMinFootHeight'])) {
    $searchMinFootHeight = $_POST['searchMinFootHeight'];
    $minFootHeightConditions = [];

    foreach ($searchMinFootHeight as $minFootHeight) {
        $minFootHeightConditions[] = "height >= '" . $minFootHeight . "'";
    }

    $minFootHeightCondition = implode(' OR ', $minFootHeightConditions);

    $condition .= trim($condition) != null ? ' AND (' . $minFootHeightCondition . ')' : '(' . $minFootHeightCondition . ')';
}

if (isset($_POST['searchMinInchHeight']) && !empty($_POST['searchMinInchHeight'])) {
    $searchMinInchHeight = $_POST['searchMinInchHeight'];
    $minInchHeightConditions = [];

    foreach ($searchMinInchHeight as $minInchHeight) {
        $minInchHeightConditions[] = "height_inches >= '" . $minInchHeight . "'";
    }

    $minInchHeightCondition = implode(' OR ', $minInchHeightConditions);

    $condition .= trim($condition) != null ? ' AND (' . $minInchHeightCondition . ')' : '(' . $minInchHeightCondition . ')';
}

if (isset($_POST['searchMaxFootHeight']) && !empty($_POST['searchMaxFootHeight'])) {
    $searchMaxFootHeight = $_POST['searchMaxFootHeight'];
    $maxFootHeightConditions = [];

    foreach ($searchMaxFootHeight as $maxFootHeight) {
        $maxFootHeightConditions[] = "height_inches <= '" . $maxFootHeight . "'";
    }

    $maxFootHeightCondition = implode(' OR ', $maxFootHeightConditions);

    $condition .= trim($condition) != null ? ' AND (' . $maxFootHeightCondition . ')' : '(' . $maxFootHeightCondition . ')';
}

if (isset($_POST['searchMaxInchHeight']) && !empty($_POST['searchMaxInchHeight'])) {
    $searchMaxInchHeight = $_POST['searchMaxInchHeight'];
    $maxInchHeightConditions = [];

    foreach ($searchMaxInchHeight as $maxInchHeight) {
        $maxInchHeightConditions[] = "height_inches <= '" . $maxInchHeight . "'";
    }

    $maxInchHeightCondition = implode(' OR ', $maxInchHeightConditions);

    $condition .= trim($condition) != null ? ' AND (' . $maxInchHeightCondition . ')' : '(' . $maxInchHeightCondition . ')';
}

if (isset($_POST['religion']) && !empty($_POST['religion'])) {
    $searchReligion = $_POST['religion'];
    $religionConditions = [];

    foreach ($searchReligion as $religion) {
        $religionConditions[] = "religion = '" . $religion . "'";
    }

    $religionCondition = implode(' OR ', $religionConditions);

    $condition .= trim($condition) != null ? ' AND (' . $religionCondition . ')' : '(' . $religionCondition . ')';
}

if (isset($_POST['source']) && !empty($_POST['source'])) {
    $searchSource = $_POST['source'];
    $sourceConditions = [];

    foreach ($searchSource as $source) {
        $sourceConditions[] = "source = '" . $source . "'";
    }

    $sourceCondition = implode(' OR ', $sourceConditions);

    $condition .= trim($condition) != null ? ' AND (' . $sourceCondition . ')' : '(' . $sourceCondition . ')';
}


}

if (isset($_POST['ddlLeadMasterType']) && trim($_POST['ddlLeadMasterType']) != null) {
    $where = ' where ';
    $condition .= trim($condition) != null ? ' and ' : ' ';
    $condition .= " lead_type = '" . $_POST['ddlLeadMasterType'] . "' ";
}

$query = "select count(*) from rishta_leadmaster " . $where . " " . $condition . " order by lead_created desc";
$usermaster = $mysqli->prepare($query);
$usermaster->execute();
$usermaster->bind_result($total_records);
$usermaster->fetch();
$usermaster->close();


$query = "select *,(select count(*) from cdi_followups where lead_id = rishta_leadmaster.lead_id) as followcount  from rishta_leadmaster " . $where . " " . $condition . " order by lead_created desc limit 100 offset " . $skip;
$usermaster = $mysqli->prepare($query);
$usermaster->execute();
$userresult = $usermaster->get_result();

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

<div class="row mtop20">
    <div class="col-md-6">
        <h4 class="subheading">Total Leads: <?php echo $total_records ?></h4>
    </div>
    <!--div class="col-md-6 text-right">
        <?php
     //   if (isset($_POST['ddlLeadMasterType']) && trim($_POST['ddlLeadMasterType']) != null) {
       //     if (trim($_POST['ddlLeadMasterType']) == 'training') {
                ?>
                <a href="manage-rishta-leads.php" id="" name="" class="btnCustom ">Reset Search</a>
                <a href="add-new-leads.php" id="btnAddNewUser2" name="btnAddNewUser" class="btnCustom">Add Lead</a>
                <?php
      //      } else {
                ?>
                <a href="manage-rishta-leads.php" id="" name="" class="btnCustom ">Reset Search</a>
                <a href="add-new-leads.php" id="btnAddNewUser1" name="btnAddNewUser" class="btnCustom ">Add Lead</a> &nbsp;&nbsp;
                <?php
      //      }
    //    } else {
            ?>
            <a href="add-new-leads.php" id="btnAddNewUser1" name="btnAddNewUser" class="btnCustom ">Add Lead</a> &nbsp;&nbsp;
            <a href="add-new-leads.php" id="btnAddNewUser2" name="btnAddNewUser" class="btnCustom">Add Lead</a>
            <?php
 //       }
        ?>
    </div-->
</div>
<div class="box-body">
    <div class="table-responsive">
        <?php
        if (mysqli_num_rows($userresult) > 0) {
            ?>
            <table class="table table-bordered table-striped">
                <thead>
                <tr>
                    <th>Sr.No</th>
                                        <th>Allocated To</th>
                                        <th>Name</th>
                                        <th>Phone Number</th>
                                        <th>Lead Status</th>
                                        <th>Email Address</th>
                                        <th>City</th>
                                        <th>State</th>
                                        <th>Country</th>
                                        <th>Created On</th>
                </tr>
                </thead>
                <tbody>
                <?php
                $i = 0;
                while ($userrow = mysqli_fetch_object($userresult)) {
                    switch ($userrow->disposition) {
                        case 'fresh':
                            $the_alert_class = 'alert-info';
                            break;
                        case 'processing':
                            $the_alert_class = 'alert-warning';
                            break;
                        case 'deal':
                            $the_alert_class = 'alert-success';
                            break;
                        case 'lost':
                            $the_alert_class = 'alert-danger';
                            break;
                        default:
                            $the_alert_class = '';
                    }
                    $i++;
                    ?>
                    <tr class="text-center alert <?php echo $the_alert_class ?>">
                                            <td><?php echo $i; ?></td>
                                            <td>
                                                <select name="" class="form-select" onchange="changeLeadAllocation(this.value,<?php echo $userrow->lead_id ?>)">
                                                    <?php
                                                    mysqli_data_seek($salesresult, 0);
                                                    while ($a_userrow = mysqli_fetch_object($salesresult)) {
                                                        ?>
                                                        <option value="<?php echo $a_userrow->user_id ?>" <?php echo $userrow->lead_allocated_to == $a_userrow->user_id ? 'selected' : ''; ?>><?php echo $a_userrow->user_full_name ?></option>
                                                        <?php
                                                    }
                                                    ?>
                                                </select>
                                            </td>
                                
                                            <td><a style="color:blue;" href="edit-leads.php?leadid=<?php echo $userrow->lead_id ?>"><?php echo $userrow->contact_name ?></a></td>
                                            <td><?php echo $userrow->contact_no ?></td>
                                            <td><?php echo $userrow->disposition ?></td>
                                            <td><?php echo $userrow->email_id ?></td>
                                            <td><?php echo $userrow->city ?></td>
                                            <td><?php echo $userrow->state ?></td>
                                            <td><?php echo $userrow->country ?></td>
                                            <td><?php echo date("m/d/Y", strtotime($userrow->lead_created_on)) ?></td>
                                            
                                        </tr>
                    <?php
                }
                ?>
                </tbody>
            </table>
    
    </div>
    
            <div align="center">
                <nav>
              
                    		<ul class="pagination">
							<?php
								$total=ceil($total_records/100);
								for($i=1;$i<=$total;$i++)
								{
								?>
									<li><a onclick='getLeadsPagination(<?php echo $i ?>)' href="javascript:void(0)" class="pagelink <?php if($i==$_POST['page_skip']) { echo "active"; } ?>"><?php echo $i ?></a></li>
								<?php	
								}
							?>
						</ul>
                </nav>
            </div>

            <?php
        } else {
            ?>
            <div class="alert alert-danger">
                <strong>Warning!</strong> You have no leads.
            </div>
            <?php
        }
        ?>
</div>