<?php

session_start();

include("../config/db.php");

if(!isset($_SESSION['user_id'])){

    header("Location:/login.php");
    exit;

}

$success = "";
$error = "";

$lead_id =
intval($_GET['id'] ?? 0);

$lead = $conn->query("
SELECT *
FROM leads
WHERE id = '$lead_id'
LIMIT 1
")->fetch_assoc();

if(!$lead){

    die("Lead no encontrado");

}

$campaign_id =
intval($lead['campaign_id']);

if(
    $_SERVER['REQUEST_METHOD'] == 'POST'
){

    $full_name =
    trim($_POST['full_name']);

    $phone =
    trim($_POST['phone']);

    $email =
    trim($_POST['email']);

    $document_number =
    trim($_POST['document_number']);

    $stmt = $conn->prepare("
    UPDATE leads
    SET
        full_name = ?,
        phone = ?,
        email = ?,
        document_number = ?
    WHERE id = ?
    ");

    $stmt->bind_param(
        "ssssi",
        $full_name,
        $phone,
        $email,
        $document_number,
        $lead_id
    );

    $stmt->execute();

    /*
    |----------------------------------------------------------------------
    | CAMPOS PERSONALIZADOS
    |----------------------------------------------------------------------
    */

    $fields = $conn->query("
    SELECT *
    FROM custom_fields
    WHERE module_name = 'leads'
    AND campaign_id = '$campaign_id'
    ORDER BY field_order ASC, id ASC
    ");

    while($field = $fields->fetch_assoc()){

        $field_key =
        'custom_'.$field['id'];

        $field_value = '';

        /*
        |------------------------------------------------------------------
        | ARCHIVOS
        |------------------------------------------------------------------
        */

        if($field['field_type'] == 'file'){

            $current = $conn->query("
            SELECT *
            FROM lead_custom_values
            WHERE lead_id = '$lead_id'
            AND field_id = '".$field['id']."'
            LIMIT 1
            ")->fetch_assoc();

            $field_value =
            $current['field_value'] ?? '';

            if(
                isset($_FILES[$field_key])
                &&
                $_FILES[$field_key]['error'] == 0
            ){

                $extension =
                strtolower(
                    pathinfo(
                        $_FILES[$field_key]['name'],
                        PATHINFO_EXTENSION
                    )
                );

                $new_name =
                time().'_'.uniqid().'.'.$extension;

                $upload_path =
                '../uploads/custom_fields/'.$new_name;

                if(
                    move_uploaded_file(
                        $_FILES[$field_key]['tmp_name'],
                        $upload_path
                    )
                ){

                    $field_value =
                    '/uploads/custom_fields/'.$new_name;

                }

            }

        } else {

            $field_value =
            trim($_POST[$field_key] ?? '');

        }

        $exists = $conn->query("
        SELECT id
        FROM lead_custom_values
        WHERE lead_id = '$lead_id'
        AND field_id = '".$field['id']."'
        LIMIT 1
        ");

        if($exists->num_rows > 0){

            $conn->query("
            UPDATE lead_custom_values
            SET field_value = '".$conn->real_escape_string($field_value)."'
            WHERE lead_id = '$lead_id'
            AND field_id = '".$field['id']."'
            ");

        } else {

            $stmt_custom = $conn->prepare("
            INSERT INTO lead_custom_values
            (
                lead_id,
                field_id,
                field_value
            )
            VALUES (?, ?, ?)
            ");

            $stmt_custom->bind_param(
                "iis",
                $lead_id,
                $field['id'],
                $field_value
            );

            $stmt_custom->execute();

        }

    }

    $success =
    "Lead actualizado correctamente.";

    $lead = $conn->query("
    SELECT *
    FROM leads
    WHERE id = '$lead_id'
    LIMIT 1
    ")->fetch_assoc();

}

?>

<!DOCTYPE html>
<html lang="es">

<head>

<meta charset="UTF-8">

<title>
Editar lead
</title>

<link rel="stylesheet" href="/assets/css/style.css">

<style>

.content-area{
    margin-left:260px;
    padding:40px;
}

.page-title{
    font-size:42px;
    font-weight:800;
    margin-bottom:10px;
}

.white-card{
    background:#fff;
    border-radius:24px;
    padding:30px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

.form-grid{
    display:grid;
    grid-template-columns:
    repeat(auto-fit,minmax(250px,1fr));
    gap:20px;
}

.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    margin-bottom:10px;
    font-weight:700;
}

.form-control{
    height:52px;
    border:none;
    background:#f1f5f9;
    border-radius:14px;
    padding:0 16px;
}

.btn-save{
    margin-top:25px;
    height:52px;
    border:none;
    border-radius:14px;
    padding:0 24px;
    background:#5b4bff;
    color:#fff;
    font-weight:700;
    cursor:pointer;
}

.success-box{
    background:#dcfce7;
    color:#166534;
    padding:16px;
    border-radius:14px;
    margin-bottom:20px;
}

.current-file{
    margin-top:10px;
}

</style>

</head>

<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

<div class="page-title">
Editar lead #<?= $lead_id ?>
</div>

<?php if($success): ?>

<div class="success-box">
<?= $success ?>
</div>

<?php endif; ?>

<div class="white-card">

<form method="POST" enctype="multipart/form-data">

<div class="form-grid">

<div class="form-group">

<label>Nombre</label>

<input
type="text"
name="full_name"
class="form-control"
value="<?= htmlspecialchars($lead['full_name']) ?>"
>

</div>

<div class="form-group">

<label>Documento</label>

<input
type="text"
name="document_number"
class="form-control"
value="<?= htmlspecialchars($lead['document_number']) ?>"
>

</div>

<div class="form-group">

<label>Teléfono</label>

<input
type="text"
name="phone"
class="form-control"
value="<?= htmlspecialchars($lead['phone']) ?>"
>

</div>

<div class="form-group">

<label>Email</label>

<input
type="email"
name="email"
class="form-control"
value="<?= htmlspecialchars($lead['email']) ?>"
>

</div>

<?php

$fields = $conn->query("
SELECT *
FROM custom_fields
WHERE module_name = 'leads'
AND campaign_id = '$campaign_id'
ORDER BY field_order ASC, id ASC
");

while($field = $fields->fetch_assoc()):

$current = $conn->query("
SELECT *
FROM lead_custom_values
WHERE lead_id = '$lead_id'
AND field_id = '".$field['id']."'
LIMIT 1
")->fetch_assoc();

$value =
$current['field_value'] ?? '';

?>

<div class="form-group">

<label>
<?= htmlspecialchars($field['field_label']) ?>
</label>

<?php if($field['field_type'] == 'textarea'): ?>

<textarea
name="custom_<?= $field['id'] ?>"
class="form-control"
style="height:120px;padding-top:15px;"
><?= htmlspecialchars($value) ?></textarea>

<?php elseif($field['field_type'] == 'file'): ?>

<input
type="file"
name="custom_<?= $field['id'] ?>"
class="form-control"
>

<?php if($value != ''): ?>

<div class="current-file">

<a
href="<?= htmlspecialchars($value) ?>"
target="_blank"
>
Ver archivo actual
</a>

</div>

<?php endif; ?>

<?php else: ?>

<input
type="<?= htmlspecialchars($field['field_type']) ?>"
name="custom_<?= $field['id'] ?>"
class="form-control"
value="<?= htmlspecialchars($value) ?>"
>

<?php endif; ?>

</div>

<?php endwhile; ?>

</div>

<button
type="submit"
class="btn-save"
>
Guardar cambios
</button>

</form>

</div>

</div>

</body>
</html>