<?php
// Database connection
$host = "192.185.25.23";
$username = "linksuda_marketing_promo";
$password = "linksuda_marketing_promo"; 
$dbname = "linksuda_marketing_promo";

// Connect to MySQL
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$response = "";
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Validate inputs
    $name = htmlspecialchars($_POST['name']);
    $id_no = htmlspecialchars($_POST['idNo']);
    $contact_no = htmlspecialchars($_POST['contactNo']);
    $province = htmlspecialchars($_POST['province']);
    $district = htmlspecialchars($_POST['district']);

    // Validate phone number length
    if (strlen($contact_no) !== 10 || !ctype_digit($contact_no)) {
        die("Invalid contact number. Please enter a 10-digit number.");
        //$response = "Invalid contact number. Please enter a 10-digit number.";
    }

    // Validate images
    if (!isset($_FILES['images']) || !isset($_FILES['imagesPage'])) {
        die("Please upload both images.");
        //$response = "Please upload both images.";
    }

    $target_dir_page = "uploads/fbPage/";
    if (!is_dir($target_dir_page)) {
        mkdir($target_dir_page, 0777, true);
    }

    $target_dir_profile = "uploads/profile/";
    if (!is_dir($target_dir_profile)) {
        mkdir($target_dir_profile, 0777, true);
    }


    // Handle profile image upload
    $profile_image = $target_dir_profile .time(). basename($_FILES["images"]["name"]);
    if (!move_uploaded_file($_FILES["images"]["tmp_name"], $profile_image)) {
        // die("Failed to upload profile image.");
        $response = "Failed to upload profile image.";
    }

    // Handle page screenshot upload
    $page_screenshot = $target_dir_page .time(). basename($_FILES["imagesPage"]["name"]);
    if (!move_uploaded_file($_FILES["imagesPage"]["tmp_name"], $page_screenshot)) {
        // die("Failed to upload page screenshot.");
        $response = "Failed to upload page screenshot.";
    }

    if($response === ""){
        // Insert data into the database
        $stmt = $conn->prepare("INSERT INTO users (name, id_no, contact_no, province, district, profile_image, page_screenshot) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssss", $name, $id_no, $contact_no, $province, $district, $profile_image, $page_screenshot);
    
        if ($stmt->execute()) {
            $response = "success"; 
        } else {
            $response = "Error: " . $stmt->error;
        }
    
        $stmt->close();
    }
}

$conn->close();

echo json_encode(['response' => $response]);
?>
