<?php
// Include database connection
include('dbconnect.php');
include('function.php');

// Set content type to JSON
header('Content-Type: application/json');

// Check if the request is a GET request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    // Retrieve data from the request
    $pcode = isset($_GET['pcode']) ? $_GET['pcode'] : null;
    $name = isset($_GET['name']) ? $_GET['name'] : null;
    $mobile = isset($_GET['mobile']) ? $_GET['mobile'] : null;
    $email = isset($_GET['email']) ? $_GET['email'] : null;
    
    // Basic field checks
    if (empty($pcode) || empty($mobile) || empty($email) || empty($name)) {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
        exit;
    }
    
    // Name validation - only alphabets and spaces allowed
    if (!preg_match('/^[a-zA-Z\s]+$/', $name)) {
        echo json_encode(['status' => 'error', 'message' => 'Name must contain only letters and spaces']);
        exit;
    }
    
    // Mobile validation - must be digits and <= 13 characters
    if (!preg_match('/^[0-9]+$/', $mobile) || strlen($mobile) > 13) {
        echo json_encode(['status' => 'error', 'message' => 'Mobile number must be numeric and not more than 13 digits']);
        exit;
    }


    $p_detail = mysqli_fetch_array(mysqli_query($conn,"SELECT * FROM tbl_project WHERE tbl_project_code='".$pcode."' AND tbl_project_flag=0"));

    // Sanitize and validate
    $project_name = $conn->real_escape_string($p_detail['tbl_project_name']);
    $mobile = $conn->real_escape_string($mobile);
    $email = $conn->real_escape_string($email);

    if (empty($project_name) || empty($mobile) || empty($email)) {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
        exit;
    }
    
    $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."'"));
	if($check_profile <= 0){
        // Create user 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',
            tbl_lead_user_profile_cdate='".date('Y-m-d H:i:s')."',
            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 info
            $source_code = isset($_GET['source']) ? $_GET['source'] : "SRC0003";
            $sorce_detail = mysqli_fetch_array(mysqli_query($conn,"SELECT tbl_lead_source_id, source_name FROM tbl_lead_source WHERE 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']);
    
            $project_id = $p_detail['tbl_project_id'];
            $location = $p_detail['tbl_project_location'];
            $assigned_date = date('Y-m-d H:i:s');
            $regdate = date('Y-m-d H:i:s');
            $cdate = date('Y-m-d H:i:s');
            $flag = '0';
            $cuser = 'Admin';
    
            // ROUND-ROBIN USER ASSIGNMENT
            $user_query = mysqli_query($conn, "
                SELECT uap.tbl_lead_user_access_projects_user_id 
                FROM tbl_lead_user_access_projects uap
                INNER JOIN tbl_invite_user iu 
                    ON uap.tbl_lead_user_access_projects_user_id = iu.id
                WHERE uap.tbl_lead_user_access_projects_project_id = '$project_id'
                AND iu.status = 'Active' 
                AND iu.flag = 0 AND iu.lead_flag = 1 
            ");
            $assigned_users = [];
            while ($row = mysqli_fetch_assoc($user_query)) {
                $assigned_users[] = $row['tbl_lead_user_access_projects_user_id'];
            }
    
            if (count($assigned_users) == 0) {
                
                $user_admin_query = mysqli_query($conn,"SELECT id from tbl_invite_user where 1 and flag=0 and role='ADMIN' and email='varun@vistaarr.com'");
                while ($row = mysqli_fetch_assoc($user_admin_query)) {
                    $assigned_users[] = $row['id'];
                }
                // echo json_encode(['status' => 'error', 'message' => 'No users assigned to this project']);
                // exit;
            }
    
            // Get last assigned user
            $tracker_query = mysqli_query($conn, "SELECT last_assigned_user_id FROM tbl_lead_assignment_tracker WHERE project_id = '$project_id'");
            $last_user_id = null;
            if ($tracker_row = mysqli_fetch_assoc($tracker_query)) {
                $last_user_id = $tracker_row['last_assigned_user_id'];
            }
    
            // Determine next user
            $next_index = 0;
            if ($last_user_id !== null) {
                $last_index = array_search($last_user_id, $assigned_users);
                if ($last_index !== false) {
                    $next_index = ($last_index + 1) % count($assigned_users);
                }
            }
            $assigned_user_id = $assigned_users[$next_index];
    
            // Update tracker
            mysqli_query($conn, "REPLACE INTO tbl_lead_assignment_tracker (project_id, last_assigned_user_id) VALUES ('$project_id', '$assigned_user_id')");
    
            // Insert lead
            $sql = "INSERT INTO tbl_lead_user (
                tbl_lead_user_profile_id,
                tbl_lead_user_mobile,
                tbl_lead_user_assigned_date,
                tbl_lead_user_source_id,
                tbl_lead_user_source_name,
                tbl_lead_user_assigned_user_id,
                tbl_lead_user_regdate,
                tbl_lead_user_cdate,
                tbl_lead_user_flag,
                tbl_lead_user_city_id,
                tbl_lead_user_cuser
            ) VALUES (
                $user_profile_id,
                '$mobile',
                '$assigned_date',
                $source_id,
                '$source_name',
                $assigned_user_id,
                '$regdate',
                '$cdate',
                $flag,
                $location,
                '$cuser'
            )";
    
            $result1 = mysqli_query($conn, $sql);
            $lead_id = $conn->insert_id;
    
            if ($result1) {
                // Send SMS (optional)
                // $sms_url = "http://pertinaxsolution.com/api/mt/SendSMS?user=Vbuzz%20Infra&password=Pert1236&senderid=VIEBRO&channel=Trans&DCS=0&flashsms=0&number=8076631024&text=%20Payye%20SAROJINI%20NAGAR%20maiPre-leased%20food%20court%20spacesBilkul%20Metro%20Station%20ke%20passSath%20mein%20paye%208%%20ki%20lease%20guaranteeCall:7428326363VIBRO&route=13&Peid=1201161491443489542&DLTTemplateId=1007787645328434291";
                // $response = file_get_contents($sms_url);
                // Send SMS to assigned user
                    $lead_name = $name;        // Example: "Kamal Tomar"
                    $project_name =getproject_name($project_id);
                    $assigned_user = get_assigned_user_name($assigned_user_id);                // Example: "Alice"
                    $mobile_number = get_assigned_user_mobile($assigned_user_id);;         // Make sure to include country code without '+'
                    
                    // Compose the message EXACTLY as per template
                    //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    
                    // Build API URL with proper encoding
                    $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                        'usr' => 'Vbuzz',
                        'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                        'smstype' => 'TextSMS',
                        'to' => $mobile_number,
                        'msg' => $message,
                        'rout' => 'Transactional',
                        'from' => 'VBuzzz',
                        'templateid' => '1607100000000347990'
                    ]);
                    
                    // Send SMS using cURL
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $sms_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    
                    // Handle errors
                    if (curl_errno($ch)) {
                        echo 'cURL error: ' . curl_error($ch);
                    } else {
                        echo 'SMS API Response: ' . $response;
                    }
                    curl_close($ch);

                    
                    // Send sms to Admin
                    // Get all active admins
                    $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
                    $result = $conn->query($sql);
                    
                    if ($result->num_rows > 0) {
                        // Loop through all admins
                        while ($row = $result->fetch_assoc()) {
                            //$assigned_user = $row['name'];
                            $mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
                    
                            // Compose message (match template exactly)
                            $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
                    
                            // Build SMS API URL
                            $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                                'usr' => 'Vbuzz',
                                'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                                'smstype' => 'TextSMS',
                                'to' => $mobile_number,
                                'msg' => $message,
                                'rout' => 'Transactional',
                                'from' => 'VBuzzz',
                                'templateid' => '1607100000000347990'
                            ]);
                    
                            // Send SMS via cURL
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $sms_url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            $response = curl_exec($ch);
                    
                            // Check for errors
                            if (curl_errno($ch)) {
                               // echo 'Error sending to ' . $assigned_user . ': ' . curl_error($ch) . "<br>";
                            } else {
                                //echo 'SMS sent to ' . $assigned_user . ': ' . $response . "<br>";
                            }
                            curl_close($ch);
                        }
                    } else {
                        echo "No admin users found.";
                    }
    
                // Link user to project
                $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', '".$p_detail['tbl_project_name']."')";
                mysqli_query($conn, $sql);
                
                $sql_lead_update="UPDATE tbl_lead_user SET tbl_lead_user_project_id='".$project_id."' where tbl_lead_user_id='".$lead_id."'";
                mysqli_query($conn, $sql_lead_update);
    
                echo json_encode(['status' => 'success', 'message' => 'Enquiry submitted successfully']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to submit enquiry']);
            }
        }
	}
	else{
	    $project_id = $p_detail['tbl_project_id'];
	    $check_profile=mysqli_fetch_array(mysqli_query($conn,"Select tbl_lead_user_profile_id,tbl_lead_user_profile_dup_count from tbl_lead_user_profile where 1 and tbl_lead_user_profile_flag=0 and tbl_lead_user_profile_mobile='".$mobile."'"));
	    $dup_count=$check_profile['tbl_lead_user_profile_dup_count']+1;
	    $update_dup_count_sql="Update tbl_lead_user_profile SET tbl_lead_user_profile_dup_count='".$dup_count."' WHERE tbl_lead_user_profile_id='".$check_profile['tbl_lead_user_profile_id']."'";
	    $update_user_profile_sql=mysqli_query($conn,$update_dup_count_sql);
	    $check_lead=mysqli_fetch_array(mysqli_query($conn,"Select * from tbl_lead_user where 1 and tbl_lead_user_profile_id= '".$check_profile['tbl_lead_user_profile_id']."'"));
	    $lead_id=$check_lead['tbl_lead_user_id'];
	    $sql = "INSERT INTO tbl_lead_user_projects (tbl_lead_user_id, tbl_lead_user_prj_id) VALUES ('$lead_id', '$project_id')";
        mysqli_query($conn, $sql);
        $sql_update="UPDATE tbl_lead_user SET tbl_lead_user_dup_project_id='".$project_id."' where tbl_lead_user_id='".$lead_id."'";
        mysqli_query($conn, $sql_update);
        if($update_user_profile_sql){
             // ROUND-ROBIN USER ASSIGNMENT
            $user_query = mysqli_query($conn, "
                SELECT uap.tbl_lead_user_access_projects_user_id 
                FROM tbl_lead_user_access_projects uap
                INNER JOIN tbl_invite_user iu 
                    ON uap.tbl_lead_user_access_projects_user_id = iu.id
                WHERE uap.tbl_lead_user_access_projects_project_id = '$project_id'
                AND iu.status = 'Active' 
                AND iu.flag = 0 AND iu.lead_flag = 1
            ");
            $assigned_users = [];
            while ($row = mysqli_fetch_assoc($user_query)) {
                $assigned_users[] = $row['tbl_lead_user_access_projects_user_id'];
            }
    
            if (count($assigned_users) == 0) {
                
                $user_admin_query = mysqli_query($conn,"SELECT id from tbl_invite_user where 1 and flag=0 and role='ADMIN' and email='varun@vistaarr.com'");
                while ($row = mysqli_fetch_assoc($user_admin_query)) {
                    $assigned_users[] = $row['id'];
                }
                // echo json_encode(['status' => 'error', 'message' => 'No users assigned to this project']);
                // exit;
            }
    
            // Get last assigned user
            $tracker_query = mysqli_query($conn, "SELECT last_assigned_user_id FROM tbl_lead_assignment_tracker WHERE project_id = '$project_id'");
            $last_user_id = null;
            if ($tracker_row = mysqli_fetch_assoc($tracker_query)) {
                $last_user_id = $tracker_row['last_assigned_user_id'];
            }
    
            // Determine next user
            $next_index = 0;
            if ($last_user_id !== null) {
                $last_index = array_search($last_user_id, $assigned_users);
                if ($last_index !== false) {
                    $next_index = ($last_index + 1) % count($assigned_users);
                }
            }
            $assigned_user_id = $assigned_users[$next_index];
    
            // Update tracker
            mysqli_query($conn, "REPLACE INTO tbl_lead_assignment_tracker (project_id, last_assigned_user_id) VALUES ('$project_id', '$assigned_user_id')");
            // Send SMS to assigned user
            $lead_name = $name;        // Example: "Kamal Tomar"
            $project_name =getproject_name($project_id);
            $assigned_user = get_assigned_user_name($assigned_user_id);                // Example: "Alice"
            $mobile_number = get_assigned_user_mobile($assigned_user_id);;         // Make sure to include country code without '+'
            
            // Compose the message EXACTLY as per template
            //$message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
            $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
            
            // Build API URL with proper encoding
            $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                'usr' => 'Vbuzz',
                'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                'smstype' => 'TextSMS',
                'to' => $mobile_number,
                'msg' => $message,
                'rout' => 'Transactional',
                'from' => 'VBuzzz',
                'templateid' => '1607100000000347990'
            ]);
            
            // Send SMS using cURL
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $sms_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            
            // Handle errors
            if (curl_errno($ch)) {
                echo 'cURL error: ' . curl_error($ch);
            } else {
                echo 'SMS API Response: ' . $response;
            }
            curl_close($ch);

            
            // Send sms to Admin
            // Get all active admins
            $sql = "SELECT name, mobile_no FROM tbl_invite_user WHERE role='ADMIN' and status='ACTIVE'";  // Update role condition if needed
            $result = $conn->query($sql);
            
            if ($result->num_rows > 0) {
                // Loop through all admins
                while ($row = $result->fetch_assoc()) {
                    //$assigned_user = $row['name'];
                    $mobile_number = $row['mobile_no'];  // Ensure mobile includes country code
            
                    // Compose message (match template exactly)
                    $message = "Hi, you have received a new lead - $lead_name for $project_name assigned to $assigned_user Vbuzz";
            
                    // Build SMS API URL
                    $sms_url = "http://sms.wishsolution.com/api/sms/SendSMS.aspx?" . http_build_query([
                        'usr' => 'Vbuzz',
                        'key' => '9374CC90-6932-4B5C-B2C1-5C7B13DF96BA',
                        'smstype' => 'TextSMS',
                        'to' => $mobile_number,
                        'msg' => $message,
                        'rout' => 'Transactional',
                        'from' => 'VBuzzz',
                        'templateid' => '1607100000000347990'
                    ]);
            
                    // Send SMS via cURL
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $sms_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
            
                    // Check for errors
                    if (curl_errno($ch)) {
                       // echo 'Error sending to ' . $assigned_user . ': ' . curl_error($ch) . "<br>";
                    } else {
                        //echo 'SMS sent to ' . $assigned_user . ': ' . $response . "<br>";
                    }
                    curl_close($ch);
                }
            } else {
                echo "No admin users found.";
            }
            echo json_encode(['status' => 'success', 'message' => 'Enquiry submitted successfully']);
        }
        else{
            echo json_encode(['status' => 'error', 'message' => 'Failed to submit duplicate enquiry']);
        }
	}

    $conn->close();

} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>
