query('SELECT id, name FROM affiliate_products ORDER BY name ASC');
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log('Database Error: ' . $e->getMessage());
$products = []; // Ensure products is an array even on error
}
// Form & AI Processing
$form_submitted = false;
$form_success = false;
$form_message = '';
$generated_script = '';
$filtered_script = '';
$ai_error = '';
$video_clips = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$form_submitted = true;
$name = htmlspecialchars($_POST['name'] ?? 'N/A');
$email = htmlspecialchars($_POST['email'] ?? 'N/A');
$topic = htmlspecialchars($_POST['topic'] ?? '');
$product_id = $_POST['product_id'] ?? null;
$selected_product = null;
if ($product_id && !empty($products)) {
foreach ($products as $p) {
if ($p['id'] == $product_id) {
$selected_product = $p;
break;
}
}
}
// 1. Send Email Notification
$email_message = "Reel Request: " . $topic;
if ($selected_product) {
$email_message .= "\nAffiliate Product: " . htmlspecialchars($selected_product['name']);
}
$to = getenv('MAIL_TO') ?: null;
$res = MailService::sendContactMessage($name, $email, $email_message, $to, 'New Reel Generation Request');
if (!empty($res['success'])) {
$form_success = true;
$form_message = 'Your request has been submitted! The AI is now generating your script below.';
} else {
$form_success = false;
$form_message = 'Sorry, there was an error sending your request. Please try again later.';
error_log('MailService Error: ' . ($res['error'] ?? 'Unknown'));
}
// 2. AI Script Generation & Filtering
if ($form_success && !empty($topic)) {
$system_prompt = 'You are an expert scriptwriter for short, high-retention social media videos. Create a script up to 60 seconds long.';
$user_prompt = 'Write a video script about: ' . $topic;
if ($selected_product) {
$user_prompt .= "\n\nIncorporate the following affiliate product naturally into the script: " . htmlspecialchars($selected_product['name']) . ".";
}
$generation_prompt = [
'input' => [
['role' => 'system', 'content' => $system_prompt],
['role' => 'user', 'content' => $user_prompt],
],
];
$generation_resp = LocalAIApi::createResponse($generation_prompt);
if (!empty($generation_resp['success'])) {
$generated_script = LocalAIApi::extractText($generation_resp);
if (!empty($generated_script)) {
$filtering_prompt = [
'input' => [
['role' => 'system', 'content' => 'You are a content moderator. Review the following script. Remove or rewrite any parts that are not compliant. Non-compliant ("haram") content includes explicit material, alcohol, pork, gambling, violence, offensive language, and religious insensitivity. Be conservative in your filtering. Output only the clean, final script. Do not add any introductory text or commentary.'],
['role' => 'user', 'content' => $generated_script],
],
];
$filtering_resp = LocalAIApi::createResponse($filtering_prompt);
if (!empty($filtering_resp['success'])) {
$filtered_script = LocalAIApi::extractText($filtering_resp);
if (empty($filtered_script)) {
$ai_error = 'The AI moderated the content but returned an empty script. This can happen with sensitive topics.';
} else {
// 3. AI Keyword Extraction
$keyword_prompt = [
'input' => [
['role' => 'system', 'content' => 'You are a keyword extraction specialist. From the following script, extract 3-5 relevant keywords for a stock video search. The keywords should be single words or short phrases that visually represent the scenes. Output only a comma-separated list of keywords. For example: "sunrise, coffee, laptop, city view".'],
['role' => 'user', 'content' => $filtered_script],
],
];
$keyword_resp = LocalAIApi::createResponse($keyword_prompt);
if (!empty($keyword_resp['success'])) {
$keywords = LocalAIApi::extractText($keyword_resp);
if (!empty($keywords)) {
// 4. Fetch Video Clips
$api_url = 'http://' . $_SERVER['HTTP_HOST'] . '/api/pexels.php?query=' . urlencode($keywords) . '&orientation=portrait';
$videos_json = @file_get_contents($api_url);
if ($videos_json) {
$videos_data = json_decode($videos_json, true);
if (!empty($videos_data['videos'])) {
$video_clips = $videos_data['videos'];
}
}
}
}
}
} else {
$ai_error = 'The AI failed to moderate the script. Error: ' . ($filtering_resp['error'] ?? 'Unknown');
error_log('AI Filtering Error: ' . ($filtering_resp['error'] ?? 'Unknown'));
}
} else {
$ai_error = 'The AI generated an empty script. Please try a different topic.';
}
} else {
$ai_error = 'The AI failed to generate a script. Error: ' . ($generation_resp['error'] ?? 'Unknown');
error_log('AI Generation Error: ' . ($generation_resp['error'] ?? 'Unknown'));
}
}
}
?>
AI Reel Generator
AI-Powered Reels. Pure Content.
Generate high-retention video scripts, automatically filtered for brand safety. Focus on your message, we'll handle the rest.