<?php
session_start();
require('../config.php');
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

if (!isset($_SESSION['client_id']) || empty($_SESSION['client_id']) || !is_numeric($_SESSION['client_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated or session expired']);
    exit;
}

$clientId = (int)$_SESSION['client_id'];

if(isset($_GET['find_invalid_contacts'])){
    $sql = "SELECT * FROM contacts WHERE client_id = '$clientId'";
    $result = mysqli_query($db, $sql);
    
    if (!$result) {
        echo json_encode(["status" => "error", "message" => mysqli_error($db)]);
        exit;
    } // ✅ This closing brace was missing!
    
    $invalidContacts = [];
    // $invalidContactsCount = 0;
    
    while ($row = mysqli_fetch_assoc($result)) {
        $contact_id = $row['id'];
        $countryCode = $row['country_code'];
        $phone = $row['phone'];
    
        $isValid = true;
    
        switch ($countryCode) {
            case '+91':
                $isValid = preg_match('/^[6-9][0-9]{9}$/', $phone);
                break;
            case '+1':
                $isValid = preg_match('/^[2-9][0-9]{9}$/', $phone);
                break;
            case '+44':
                $isValid = preg_match('/^7[0-9]{9}$/', $phone);
                break;
            default:
                $isValid = false;
                break;
        }
    
        if (!$isValid) {
            // $invalidContactsCount++;
            // $invalidContacts[] = [
            //     'country_code' => $countryCode,
            //     'phone' => $phone
            // ];
            $invalidContacts[] = $contact_id;
        }
    }
    
    echo json_encode(["status" => "success", "invalidContacts" => $invalidContacts]);
}

if(isset($_GET['delete_invalid_contacts'])){
    if(!isset($_POST['invalid_contacts']) || empty($_POST['invalid_contacts'])){
        echo json_encode(["status"=>"error", "message"=>"Missing Field: invalid_contacts", "post_data" => $_POST]);
        exit;
    } 
    $invalid_contacts = $_POST['invalid_contacts'];

    $sql = "DELETE FROM contacts WHERE id IN ($invalid_contacts) AND client_id = '$clientId' ";
    // echo json_encode(["status"=>"error", "message"=> $sql]);
    // exit;
    if(!mysqli_query($db, $sql)){
        echo json_encode(["status"=>"error", "message"=> mysqli_error($db)]);
        exit;
    }

    echo json_encode(["status"=>"success", "message"=> "Invalid Contacts Deleted Successfully!"]);
}

?>
