<?php

// Database connection
$host = "localhost";  // Change this if using a remote database
$user = "sheriakiganjani_sheria";
$pass = "pqa0}j^QoDWu";
$dbname = "sheriakiganjani_sheria";


// Connect to database
$conn = new mysqli($host, $user, $pass, $dbname);

// Check connection
if ($conn->connect_error) {
    die(json_encode(["status" => "error", "message" => "Database connection failed: " . $conn->connect_error]));
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(["status" => "error", "message" => "Invalid request method"]));
}

// Extract POST fields
$api_key = $_POST['api_key'] ?? '';
$opportunity_id = $_POST['opportunity_id'] ?? '';
$opportunity_type = $_POST['opportunity_type'] ?? '';
$full_name = $_POST['full_name'] ?? '';
$phone_number = $_POST['phone_number'] ?? '';
$email = $_POST['email'] ?? '';
$cover_letter = $_POST['cover_letter'] ?? '';

// Validate API Key (Replace with your actual key)
$valid_api_key = "YTc4YWY3ZWVlZWViODU3YTY5ODUzNTA4ZGU3YzVhYzM1NTdjNjM1MWEyYzA1ODU1ZDhlqA12AjkP0qNTc4ZjU3N2QwMDVmMw==";
if ($api_key !== $valid_api_key) {
    die(json_encode(["status" => "error", "message" => "Invalid API Key"]));
}

// Check for required fields
if (empty($opportunity_id) || empty($opportunity_type) || empty($full_name) || empty($phone_number) || empty($email)) {
    die(json_encode(["status" => "error", "message" => "Missing required fields"]));
}

// Handle file upload
$file_path = "";
if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $upload_dir = "opportunitiesfolder/";
    

    $file_name = basename($_FILES["file"]["name"]);
    $file_path = $upload_dir . time() . "_" . $file_name;

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $file_path)) {
        // File successfully uploaded
    } else {
        die(json_encode(["status" => "error", "message" => "File upload failed"]));
    }
}

// Insert data into database
$sql = "INSERT INTO tbl_oppinput (`opp_id`,`fullname`,`email`,`phone_number`,`cover_leter`,`file_name`,`app_status`,`opp_type`)
        VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param $pportunity_id, $opportunity_type, $full_name, $phone_number, $email, $cover_letter, $file_path);

if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "Opportunity submitted successfully"]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to insert data"]);
}

// Close the statement and connection
$stmt->close();
$conn->close();

?>
