<?php
session_start();
include_once 'config/db.php';

// Ensure the admin is logged in
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: admin_login.php');
    exit;
}

// Get user ID from URL or Form
$user_id = isset($_POST['user_id']) ? $_POST['user_id'] : (isset($_GET['id']) ? $_GET['id'] : '');

// Fetch user details for sending SMS
$stmt = $pdo->prepare("SELECT contact_no, profile_link, customer_name FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    die("User not found.");
}

$contact_no = $user['contact_no'];
$profile_link = $user['profile_link'];
$customer_name = $user['customer_name'];

// Handle the form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $description = $_POST['description'];
    $date = $_POST['date'];

    // Handle image uploads
    $image_paths = [];
    if (!empty($_FILES['images']['name'][0])) {
        if (!is_dir('uploads/images')) {
            mkdir('uploads/images', 0777, true);
        }

        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            $file_name = uniqid() . "_" . $_FILES['images']['name'][$key];
            $file_path = "uploads/images/" . $file_name;
            move_uploaded_file($tmp_name, $file_path);
            $image_paths[] = $file_path;
        }
    }

    // Handle video upload
    $video_path = null;
    if (!empty($_FILES['video']['name'])) {
        if (!is_dir('uploads/videos')) {
            mkdir('uploads/videos', 0777, true);
        }

        $video_name = uniqid() . "_" . $_FILES['video']['name'];
        $video_path = "uploads/videos/" . $video_name;
        move_uploaded_file($_FILES['video']['tmp_name'], $video_path);
    }

    // Insert into final_look table
    $stmt = $pdo->prepare("INSERT INTO final_look (user_id, description, image, video_url, date, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$user_id, $description, json_encode($image_paths), $video_path, $date]);

    // Update user status to 'Completed'
    $updateStmt = $pdo->prepare("UPDATE users SET status = 'Completed' WHERE id = ?");
    $updateStmt->execute([$user_id]);

    // Send SMS notification with status update
    $sms_message = "Hello $customer_name, your profile has been updated. Status: Completed. View your profile here: https://blog.onedriveme.com/profile.php?link=$profile_link";
    
    // Send SMS via Notify.lk API
    $user_api_id = '29008'; // Your User ID
    $api_key = 'HwPmIPEriPmyEOVOmfhp'; // Your API Key
    $sender_id = 'BnS INT'; // Your approved Sender ID

    // Prepare the URL for sending the SMS
    $sms_url = "https://app.notify.lk/api/v1/send?user_id=$user_api_id&api_key=$api_key&sender_id=$sender_id&to=$contact_no&message=" . urlencode($sms_message);

    // Send the request
    $response = file_get_contents($sms_url);

    // Check if SMS sent successfully
    if ($response === FALSE) {
        $sms_status = 'fail';
        $sms_message = 'Error sending SMS. Please check the number or try again later.';
    } else {
        $sms_status = 'success';
        $sms_message = 'SMS sent successfully';
    }

    // Redirect to the customer list page with the status and message
    header('Location: customer-list.php?sms_status=' . $sms_status . '&sms_message=' . urlencode($sms_message));
    exit;
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('partials/head.php'); ?>
    <style>
        .image-preview { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
        .image-preview div { position: relative; }
        .image-preview img { width: 100px; height: 100px; object-fit: cover; border-radius: 5px; }
        .delete-icon { position: absolute; top: 0; right: 0; background: red; color: white; border-radius: 50%; cursor: pointer; padding: 2px 6px; }
    </style>
</head>
<body>
    <div class="main-wrapper">
        <?php include('partials/header.php'); ?>
        <?php include('partials/sidebar.php'); ?>

        <div class="page-wrapper">
            <div class="content">
                <div class="page-header mb-3">
                    <h4>Create Appearance Record</h4>
                </div>

                <div class="row">
                    <div class="col-xl-6 d-flex">
                        <div class="card flex-fill">
                            <div class="card-header">
                                <h5 class="card-title">Appearance Information</h5>
                            </div>
                            <div class="card-body">
                                <form method="POST" action="" enctype="multipart/form-data">
                                    <input type="hidden" name="user_id" value="<?= htmlspecialchars($user_id) ?>">

                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea name="description" class="form-control" rows="4" required></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Select Date</label>
                                        <input type="date" name="date" class="form-control" required>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Upload Images</label>
                                        <input type="file" name="images[]" class="form-control" accept="image/*" multiple onchange="previewImages(event)">
                                        <div class="image-preview" id="imagePreview"></div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Upload Video</label>
                                        <input type="file" name="video" class="form-control" accept="video/*">
                                    </div>

                                    <button type="submit" class="btn btn-success">Submit</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <?php include('partials/footer.php'); ?>

    <script>
        function previewImages(event) {
            let imagePreview = document.getElementById("imagePreview");
            imagePreview.innerHTML = "";

            for (let file of event.target.files) {
                let reader = new FileReader();
                reader.onload = function(e) {
                    let div = document.createElement("div");
                    let img = document.createElement("img");
                    img.src = e.target.result;

                    let deleteIcon = document.createElement("span");
                    deleteIcon.innerHTML = "×";
                    deleteIcon.classList.add("delete-icon");
                    deleteIcon.onclick = function() { div.remove(); };

                    div.appendChild(img);
                    div.appendChild(deleteIcon);
                    imagePreview.appendChild(div);
                };
                reader.readAsDataURL(file);
            }
        }
    </script>
</body>
</html>
