summaryrefslogtreecommitdiff
path: root/src/gemini/Controller/Village.php
blob: 81a599a87b36cfc41c26c3aff7ecb3040abc038c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
<?php

namespace App\gemini\Controller;

use App\DB;
use App\Guard;
use App\Model\Event;
use App\Model\Event\SendResources;
use App\Model\Event\SendResourcesCarriers;
use App\Model\Event\SendUnits;
use App\Model\Event\TrainUnits;
use App\Model\Event\UpgradeBuilding;
use App\Model\Unit;
use App\Model\Unit\MailCarrier;
use App\Model\Village as Model;
use App\Support\ResourceType;
use App\View;
use GeminiFoundation\Request;
use GeminiFoundation\Response;
use GeminiFoundation\Status;

class Village
{
  // #[Route(path: '/villages', methods: ['GET'])]
  public function list(): Response
  {
    $villages = DB::fetch(
      Model::class,
      <<<SQL
      select *,villages.id from villages
      join user_villages on villages.id = user_villages.village_id
      where user_villages.user_id=:id
      SQL,
      ['id' => $_SESSION['user']['id']]
    );


    return new Response(body: View::render('villages.twig', [
      'villages' => $villages,
    ]));
  }

  //#[Route(path: '/village/{x}/{y}', methods: ['GET'])]
  public function show(Request $request): Response
  {
    $village = Model::getByCoordinates($request->get('x'), $request->get('y'));

    if (! Guard::ownsVillage($village->id)) {
      return new Response(body: View::render('error.twig', ['message' => 'Insufficient permission']));
    }

    $events = [];

    $eventsBuilding = DB::query(
      <<<SQL
      select * from events_upgrade_building as event
      left join events on event.event_id = events.id
      where events.village_id=:id
      SQL, ['id' => $village->id]
    )->fetchAll();

    foreach ($eventsBuilding as $row) {
      $events['UpgradeBuilding'][$row['type']][] = DB::convertToModel(UpgradeBuilding::class, $row);
    }

    $eventsUnits = DB::query(
      <<<SQL
      select * from events_train_units as event
      left join events on event.event_id = events.id
      where village_id=:id
      SQL, ['id' => $village->id]
    )->fetchAll();

    foreach ($eventsUnits as $row) {
      $events['TrainUnits'][] = DB::convertToModel(TrainUnits::class, $row);
    }

    $eventsUnitsSendOwn = DB::query(
      <<<SQL
      select * from events_send_units as event
      left join events on event.event_id = events.id
      where village_id=:id
      SQL, ['id' => $village->id]
    )->fetchAll();

    $eventsUnitsSendOther = DB::query(
      <<<SQL
      select * from events_send_units as event
      left join events on event.event_id = events.id
      where (destination=:id or source=:id) and village_id!=:id and is_canceled=false
      SQL, ['id' => $village->id]
    )->fetchAll();

    foreach ([...$eventsUnitsSendOwn, ...$eventsUnitsSendOther] as $row) {
      $events['SendUnits'][] = DB::convertToModel(SendUnits::class, $row);;
    }

    $eventsResourcesSendOwn = DB::query(
      <<<SQL
      select * from events_send_resources as event
      left join events on event.event_id = events.id
      where village_id=:id
      SQL, ['id' => $village->id]
    )->fetchAll();

    $eventsResourcesSendOther = DB::query(
      <<<SQL
      select * from events_send_resources as event
      left join events on event.event_id = events.id
      where (destination=:id or source=:id) and village_id!=:id and is_canceled=false
      SQL, ['id' => $village->id]
    )->fetchAll();

    foreach ([...$eventsResourcesSendOwn, ...$eventsResourcesSendOther] as $row) {
      $events['SendResources'][] = DB::convertToModel(SendResources::class, $row);;
    }

    $eventsResourcesCarriersSendOwn = DB::query(
      <<<SQL
      select * from events_send_resources_carriers as event
      left join events on event.event_id = events.id
      where village_id=:id
      SQL, ['id' => $village->id]
    )->fetchAll();

    $eventsResourcesCarriersSendOther = DB::query(
      <<<SQL
      select * from events_send_resources_carriers as event
      left join events on event.event_id = events.id
      where (destination=:id or source=:id) and village_id!=:id
      SQL, ['id' => $village->id]
    )->fetchAll();

    foreach ([...$eventsResourcesCarriersSendOwn, ...$eventsResourcesCarriersSendOther] as $row) {
      $events['SendResourcesCarriers'][] = DB::convertToModel(SendResourcesCarriers::class, $row);;
    }

    $buildings = [];
    foreach (Model::getBuildings($village->id, true) as $building) {
      $buildings[$building->type] = $building;
    }


    return new Response(body: View::render('village.twig', [
      'village' => $village,
      'events' => $events,
      'buildings' => $buildings,
      'villages' => DB::fetch(Model::class, "select * from villages where id!=:id", ['id' => $village->id]),
      'postOffice' => $village->getBuilding($village->id, 'PostOffice'),
    ]));
  }

  // #[Route(path: '/village/{x}/{y}/storage/config', methods: ['POST'])]
  public function storageConfig(Request $request): Response
  {
    $village = Model::getByCoordinates($request->get('x'), $request->get('y'));
    $type = $request->get('type');

    if (empty($type)) {
      return new Response(body: View::render('storage.twig', [
        'village' => $village,
      ]));
    }

    if (empty($request->get('input'))) {
      return new Response(statusCode: Status::INPUT, meta: "$type percent?");
    }

    $input = intval($request->get('input'));

    // calculate to max 100%
    $allTypes = ResourceType::asProperties();
    $allOtherTypes = array_diff($allTypes, [$type]);

    $storageConfig = $village->getStorageConfig($village->id);

    $values = [];
    foreach ($allTypes as $resourceType) {
      $values[$resourceType] = $storageConfig->$resourceType;
    }
    $values[$type] = $input;

    $total = 0;
    foreach ($values as $value) {
      $total += $value;
    }

    foreach ($values as $resourceType => $value) {
      $values[$resourceType] = round(($value / $total) * 100);
    }

    if ($values[$type] !== $input) {
      $values[$type] = $input;
    }

    $newTotal = array_sum($values);
    $values['food'] += (100 - $newTotal);

    DB::query(
      <<<SQL
      update village_storage_config
      set wood=:wood, clay=:clay, iron=:iron, food=:food
      where village_id=:id
      SQL,
      ['wood' => $values['wood'], 'clay' => $values['clay'], 'iron' => $values['iron'], 'food' => $values['food'], 'id' => $village->id]
    );


    return new Response(
      statusCode: Status::REDIRECT_TEMPORARY,
      meta: "/village/{$village->x}/{$village->y}/storage/config"
    );
  }

  // #[Route(path: '/village/{x}/{y}/send-resources', methods: ['POST'])]
  public function sendResources(Request $request): Response
  {
    $village = Model::getByCoordinates($request->get('x'), $request->get('y'));

    $selectedResourceType = $request->get('selectedResourceType');
    if (empty($selectedResourceType)) {
      return new Response(body: View::render('send-resources/01-resource-types.twig', [
        'village' => $village,
        'postOffice' => $village->getBuilding($village->id, 'PostOffice'),
      ]));
    }

    if (empty($request->get('selectedVillageX'))) {
      return new Response(body: View::render('send-resources/02-villages.twig', [
        'village' => $village,
        'villages' => DB::fetch(Model::class, "select * from villages where id!=:id", ['id' => $village->id]),
        'selectedResourceType' => $selectedResourceType,
        'postOffice' => $village->getBuilding($village->id, 'PostOffice'),
      ]));
    }
    $selectedVillage = Model::getByCoordinates($request->get('selectedVillageX'), $request->get('selectedVillageY'));

    $amount = intval($request->get('input'));
    if (empty($amount)) {
      return new Response(statusCode: Status::INPUT, meta: 'Amount');
    }

    $resourceCapabilities = MailCarrier::getResourceCapabilities($village);
    $necessaryMailCarriers = ceil($amount / $resourceCapabilities);
    $mailCarriers = DB::fetch(MailCarrier::class, 'select sum(amount) as amount from village_units where type=:type and residence_village_id=:villageId and is_traveling=false', ['villageId' => $village->id, 'type' => 'MailCarrier'])[0]->amount ?? 0;
    if ($mailCarriers === 0 || $amount > $resourceCapabilities) {
      return new Response(
        statusCode: Status::REDIRECT_TEMPORARY,
        meta: "/village/{$village->x}/{$village->y}/send-resources/type/$selectedResourceType"
      );
    }

    $destination = $selectedVillage;

    // event
    $event = new Event();
    $event->time = (new \DateTime())->add(
      \DateInterval::createFromDateString(
        Unit::getTravelTime(new MailCarrier(), Model::getDistance($village->x, $village->y, $destination->x, $destination->y))
        . ' seconds'
      )
    );
    $event->villageId = $village->id;
    $sendResourcesEvent = new SendResources();
    $sendResourcesEvent->event = $event;
    $sendResourcesEvent->$selectedResourceType = $amount;
    $sendResourcesEvent->source = $village->id;
    $sendResourcesEvent->destination = $destination->id;
    $sendResourcesEvent->dbInsert();


    return new Response(
      statusCode: Status::REDIRECT_TEMPORARY,
      meta: "/village/{$village->x}/{$village->y}"
    );
  }
}